Python:splitlines()从文本文件中删除,然后将它们写回文本文件
我正在制作一个python程序,从网站获取数据,然后将其记录在文本文件中。我想用4个和一个字符串hello条目记录我正在测试的最后1000个条目,并删除其余的条目。以下是我到目前为止的情况:Python:splitlines()从文本文件中删除,然后将它们写回文本文件,python,Python,我正在制作一个python程序,从网站获取数据,然后将其记录在文本文件中。我想用4个和一个字符串hello条目记录我正在测试的最后1000个条目,并删除其余的条目。以下是我到目前为止的情况: 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 = 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
你能帮我弄明白吗,看起来是这样的:
hello
'hello\n''\'hello\\n\'\'\\\'hello\\\\n\\\'\\\'\\\\\\\'hello\\\\\\\\n\\\\\\\'"\\\\\\\'hello\\\\\\\\\\\\\\\\n\\\\\\\'"\\\'\''
hello
hello
hello
hello
谢谢大家! 使用deque,因为它提供maxlen。添加行/字将只保留最大项目,添加新项目,忘记旧项目
from collections import deque
fname = "source.txt"
last_lines = deque(maxlen = 4)
with open(fname) as f:
text = f.read()
for line in text.splitlines(True):
last_lines.append(line)
#f is closed when we leave the block
outfname = fname
with open(outfname, "w") as of:
for line in last_lines:
of.write(line)
即使没有分隔线,您也可以这样做,但这是您自找的
from collections import deque
fname = "source.txt"
last_lines = deque(maxlen = 4)
for line in open(fname):
last_lines.append(line)
#file is closed when we leave the (for) block
outfname = fname
with open(outfname, "w") as of:
for line in last_lines:
of.write(line)
使用Jon Clements的技巧,使用由文件描述符生成的迭代器创建deque,并允许自己使用不同的源文件和目标文件,它可以非常短:
from collections import deque
with open("target.txt", "w") as out_f:
for line in deque(open("source.txt"), maxlen = 4):
out_f.write(line)
你想要最后1000个非空行吗?我不确定您是否在这里选择了过滤方案。您是否意识到,您先打开文件进行读取,然后在不关闭文件的情况下,再次尝试打开文件进行写入?我建议在第3行附近添加f,看看情况是否有所改善。为了保持代码清晰,在打开文件进行写入之前,content=text.splitlinesTrue会更适合。我将其更改为:f=opentest.txt,r text=f.read content=text.splitlinesTrue f.close f=opentest.txt,w f.writehello f.write\n,范围为0,4:f.writestruction[x:x+1]。去掉“[]”f.close,没有任何改进。