我需要逐行写一个文本文件.此代码逐行打印文本,但只有最后一行存储在result.txt文件中.
import re
import fileinput
for line in fileinput.input("test.txt"):
new_str = re.sub('[^a-zA-Z0-9\n\.]'," ", line)
print new_str
open('result.txt', 'w').write(new_str)
Run Code Online (Sandbox Code Playgroud)
我不知道为什么你需要fileinput模块,open也可以处理这种情况.
你的for循环遍历所有行并覆盖 new_str新行.最后一行没有下一行,因此不会被覆盖,因此它是唯一可以保存的行.
import re
test_f = open('test.txt')
result_f = open('result.txt', 'a')
for line in test_f:
new_str = re.sub('[^a-zA-Z0-9\n\.]'," ", line)
result_f.write(new_str)
# also, this too, please:
test_f.close()
result_f.close()
Run Code Online (Sandbox Code Playgroud)with即使代码崩溃,您也应该使用该语句自动关闭文件.
import re
with open('test.txt') as test_f, open('result.txt', 'w') as result_f:
for line in test_f:
new_str = re.sub('[^a-zA-Z0-9\n\.]'," ", line)
result_f.write(new_str)
Run Code Online (Sandbox Code Playgroud)