Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
假设我有一个文本文件(名为 test.txt),之前在我的 Python 脚本中我已经在其中写入了 15 行。现在,我想在该文件中添加一些行。如何从 test.txt 的第 16 行开始迭代并在 Python 中添加一些新行?
要在文件末尾追加,您不需要“迭代”它——只需在追加模式下打开它:
with open("my_file", "a") as f: f.write("another line\n")
遍历文件可以用来读取它们,而不是用来写入它们。
当您“打开”文件时,使用常规
f = open(FILE)
你应该说明你正在使用的方法,在这种情况下,追加,所以
f = open(FILE, 'a')