【问题标题】:does ('filename','w') replace or add [closed]是否('filename','w')替换或添加[关闭]
【发布时间】:2020-11-03 00:19:16
【问题描述】:

如果我有一个名为“文件”的文件,上面写着

thing1

thing2

我做到了

f = open('file','w')
f.write('hi'+'\n')
f.close()

文件会变成

thing1

thing2

hi

hi

编辑:在测试这个时,我做了一个代码说

new_un = open('usernames', 'w')
for i in range(len(usernames)):
    new_un.write(usernames[i]+'\n')
new_un.close()

它会在用户名列表中写入所有内容。 我认为如果它是压倒一切的,那么它将只有列表中的最后一件事

【问题讨论】:

  • 文件将被覆盖。如果要附加到文件,请使用 'a' 而不是 'w'
  • 是什么阻止你在解释器中尝试这个?
  • w: Opens in write-only mode. The pointer is placed at the beginning of the file and this will overwrite any existing file with the same name. It will create a new file if one with the same name doesn't exist. 可能想要a: Opens a file for appending new information to it. The pointer is placed at the end of the file. A new file is created if one with the same name doesn't exist.
  • 尝试这个比在这里问这个更痛苦!大声笑

标签: python


【解决方案1】:
f = open('file','w')
f.write('hi'+'\n')
f.close()

output: "hi" in file 没有别的,这是因为 'w' 会覆盖文件,导致在输入文本之前它是空白的,

f = open('file','a')
f.write('hi'+'\n')
f.close()

输出以文本文件开头的任何内容 + "Hi",这会将文本添加到文件中

f = open('file','r')
f.write('hi'+'\n')
f.close()

输出错误,因为您打开文件进行读取,因此您无法添加文本

【讨论】:

    猜你喜欢
    • 2014-04-03
    • 2015-03-26
    • 2013-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    • 2022-10-13
    • 1970-01-01
    相关资源
    最近更新 更多