【发布时间】: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