截断文本文件不会更改文件 [英] truncating a text file does not change the file

查看:160
本文介绍了截断文本文件不会更改文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当一个新手(像我一样)要求阅读/处理Python中的文本文件时,他经常得到如下答案:

 与开放(input.txt,r)作为f:
在f:
#你的东西

现在我想在特殊的一行之后截断我正在阅读的文件中的所有内容。在修改上面的例子之后,我使用:

 与open(input.txt,'r +')作为文件:
为文件行:
print line.rstrip(\\\
\r)#for debug
如果line.rstrip(\\\
\r)==CC :
printtruncating! #for debug
file.truncate();
break;

,并期望在看到第一个CC后丢弃所有内容。在input.txt上运行这段代码:

  AA 
CC
DD


$ b

以下是打印在控制台上(如预期的那样):

  AA 
CC
截断!

但文件input.txt保持不变!?!?



这怎么可能?我在做什么错了?



编辑:在操作后,我希望文件包含:

  AA 
CC


解决方案

除了glibdud的回答之外,truncate()还需要删除内容的位置。您可以通过 tell()命令获取文件中的当前位置。正如他所提到的,通过使用for循环, next()禁止像tell这样的命令。但是在建议的while循环中,可以在当前的tell() - 位置截断。因此,完整的代码如下所示:

Python 3:

 打开(test.txt,'r +')作为文件:
line = file.readline()
while line:
print(line.strip())
如果line.strip()==CC:
print(truncating)
file.truncate(file.tell())
break
line = file。 readline()


When a novice (like me) asks for reading/processing a text file in python he often gets answers like:

with open("input.txt", 'r') as f:
    for line in f:
        #do your stuff

Now I would like to truncate everything in the file I'm reading after a special line. After modifying the example above I use:

with open("input.txt", 'r+') as file:
    for line in file:
        print line.rstrip("\n\r") #for debug
        if line.rstrip("\n\r")=="CC":
           print "truncating!"  #for debug
           file.truncate();
           break;

and expect it to throw away everything after the first "CC" seen. Running this code on input.txt:

AA
CC
DD

the following is printed on the console (as expected):

AA
CC
truncating!

but the file "input.txt" stays unchanged!?!?

How can that be? What I'm doing wrong?

Edit: After the operation I want the file to contain:

AA
CC

解决方案

In addition to glibdud's answer, truncate() needs the size from where it deletes the content. You can get the current position in your file by the tell() command. As he mentioned, by using the for-loop, the next() prohibits commands like tell. But in the suggested while-loop, you can truncate at the current tell()-position. So the complete code would look like this:

Python 3:

with open("test.txt", 'r+') as file:
line = file.readline()
while line:
    print(line.strip())
    if line.strip() == "CC":
        print("truncating")
        file.truncate(file.tell())
        break
    line = file.readline()

这篇关于截断文本文件不会更改文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆