如何使用Python正确截断文本文件?

时间:2018-03-02 08:03:43

标签: python

我想在阅读其内容后截断我的文件,但它似乎没有这样做,并且在文件的添加是在现有内容之后而不是文件的开头。

我的代码如下:

from sys import argv
script, filename = argv
prompt= '??'

print("We're going to erase %r." %filename)
print("If you don't want that, hit CTRL-C.")
print("If you do want it, hit ENTER.")
input(prompt)

print("Opening the file...")
target = open(filename,'r+')
print(target.read())
print("I'm going to erase the file now!")


print("Truncating the file. Goodbye!")  
target.truncate()

print("Now I'm going to ask you 3 lines:")
line1 = input('Line 1: ')
line2 = input('Line 2: ')
line3 = input('Line 3: ')

print("I'm going to write these to the file now!")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("And finally we close the file! Please check and see if the file 
    has been modified!")
target.close()         

2 个答案:

答案 0 :(得分:1)

要将文件截断为零字节,您只需使用写访问权限打开它,无需实际编写任何内容。它可以简单地完成:

with open(filename, 'w'): pass

但是,使用您的代码需要在截断之前将当前文件位置重置为文件的开头:

....
print("Truncating the file. Goodbye!")  
target.seek(0)                            # <<< Add this line
target.truncate() 
....

示例运行(脚本为gash.py):

$ echo -e 'x\ny\nz\n' > gash.txt
$ python3 gash.py gash.txt
We're going to erase 'gash.txt'.
If you don't want that, hit CTRL-C.
If you do want it, hit ENTER.
??
Opening the file...
x
y
z


I'm going to erase the file now!
Truncating the file. Goodbye!
Now I'm going to ask you 3 lines:
Line 1: one
Line 2: two
Line 3: three
I'm going to write these to the file now!
And finally we close the file! Please check and see if the file has been modified!
$ cat gash.txt
one
two
three
$

答案 1 :(得分:0)

截断只写:

f = open('filename', 'w')
f.close()