2013-10-09 101 views
1

我正在制作一个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 

谢谢!

+0

你想要的最后1000个非空行?我不确定你在这里过滤方案。 – GWW

+0

您是否意识到,您首先打开文件进行阅读,然后在未关闭文件的情况下尝试再次打开文件进行阅读?我建议在第3行添加'f.close()',看看情况是否改善。为了保持代码清晰,在打开文件进行写入之前,'content = text.splitlines(True)'会更好。 –

+0

我改成了这样:'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

回答

0

使用deque,因为它提供maxlen。添加行/单词将只保留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) 

而使用的伎俩从乔恩·克莱门茨(创建双端队列使用从文件描述符作出迭代器),并允许自己使用不同的源文件和目标文件,它可以变得很短:

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) 
+0

谢谢,它效果很好! – pclever1

相关问题