python - 在 python 中使用 "w"模式有什么意义?

标签 python

#From the sys package, i'm importing the argv
from sys import argv
#Un packaging the arguments
script, filename = argv 
#Print statements
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
#To accept whether or not we want to continue or not
raw_input("?")

print "Opening the file..."
# I am opening the file
target = open(filename)

print "Truncating the file. Goodbye!"
target.truncate()

print "Now i'm going to ask you for three lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "I'm going to write these to the file."
x = "%r\n %r\n %r\n" % (line1, line2, line3)
target.write(x)
#This also works to write the files
# target.write ("%r\n%r\n%r\n" % (line1, line2, line3))

print "And finally, we close it."
target.close()

对于 open(filename),我发现当我将脚本付诸行动时得到的结果与 open(filename "w")

相同

那么“w”有什么意义呢?因为我已经有了使用 target.write() 命令写入的函数!

最佳答案

“w”模式如果文件不存在则创建文件,如果存在则清空它。

关于python - 在 python 中使用 "w"模式有什么意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17644668/

相关文章:

python - 当我尝试转换 Keras MLP 时,为什么 Google Colab 会给出 "unknown device"错误?

python - 使用 BeautifulSoup 查找顶级标签

python - npm 安装 bcrypt,gyp 错误! Python

android - 在使用 python 编码的 Android 应用程序中使用蓝牙

python - 相当于 Python 的 Swift URL 字符串模板

python - 长格式 Pandas 数据框到字典

python - Pandas Timedelta 以月为单位

python - 递归函数,在字典中查找(x步)所有可能的路径

python - 涉及列表的格式问题

python - matplotlib scatter_hist 在直方图中具有 stepfilled histt​​ype