python 中的 a+ 命令读取但不附加
a+ command in python reads but does not append
例如,我有一个包含 4 行语句“this is shirin”的文本文件,当我 运行 以下代码在我的文件中没有任何反应时:
file = open('test.txt', 'a+')
for i in file:
if len(i) == 0 or 'this' in i:
file.write('test')
file.close()
当你以追加方式打开文件时,初始位置在末尾,因此没有可读取的内容,循环立即结束。您需要倒回文件的开头才能阅读。而如果想继续看下去,写到最后还需要重新寻找。
with open('test.txt', 'a+') as file:
file.seek(0)
while True:
i = file.readline()
if not i:
break
oldpos = file.tell()
if 'this' in i:
file.write('test')
file.seek(oldpos)
例如,我有一个包含 4 行语句“this is shirin”的文本文件,当我 运行 以下代码在我的文件中没有任何反应时:
file = open('test.txt', 'a+')
for i in file:
if len(i) == 0 or 'this' in i:
file.write('test')
file.close()
当你以追加方式打开文件时,初始位置在末尾,因此没有可读取的内容,循环立即结束。您需要倒回文件的开头才能阅读。而如果想继续看下去,写到最后还需要重新寻找。
with open('test.txt', 'a+') as file:
file.seek(0)
while True:
i = file.readline()
if not i:
break
oldpos = file.tell()
if 'this' in i:
file.write('test')
file.seek(oldpos)