我正在制作一个python程序,从网站获取数据,然后将其记录在文本文件中。我希望这记录最后1000(我正在测试4和字符串“你好”)条目,并删除其余的。以下是我迄今为止:Python:从文本文件splitlines(),然后将它们写回文本文件
f = open("test.txt", "r")
text = f.read()
f = open("test.txt", "w")
content = text.splitlines(True)
f.write("hello")
f.write("\n")
for x in range(0,4):
f.write(str(content[x:x+1]).strip('[]'))
f.close()
这个“作品”,然而格式化文本文件是这样的:
hello
'hello\n''\'hello\\n\'\'\\\'hello\\\\n\\\'\\\'\\\\\\\'hello\\\\\\\\n\\\\\\\'"\\\\\\\'hello\\\\\\\\\\\\\\\\n\\\\\\\'"\\\'\''
你能不能帮我弄清楚了这一点,所以它看起来是这样的:
hello
hello
hello
hello
谢谢!
你想要的最后1000个非空行?我不确定你在这里过滤方案。 – GWW
您是否意识到,您首先打开文件进行阅读,然后在未关闭文件的情况下尝试再次打开文件进行阅读?我建议在第3行添加'f.close()',看看情况是否改善。为了保持代码清晰,在打开文件进行写入之前,'content = text.splitlines(True)'会更好。 –
我改成了这样:'F =开放( “test.txt的”, “R”) 文本= f.read() 含量= text.splitlines(真) f.close() F =开放( “test.txt的”, “W”) f.write( “你好”) f.write( “\ n” 个) 在范围X(0,4): \t f.write(STR (content [x:x + 1])。strip('[]')) f.close()'并没有改进。 – pclever1