Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python正确截断文本文件?_Python - Fatal编程技术网

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

如何使用Python正确截断文本文件?,python,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

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

我的代码如下:

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()         

要截断,只需编写:

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

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

with open(filename, 'w'): pass
但是,使用您的代码,您需要在截断之前将当前文件位置重置为文件的开头:

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

不。截断删除当前位置后的所有内容?在您的情况下,就像您刚才所说的那样。读取所有内容,没有什么需要截断的。不需要f.write或f.truncate,具有写访问权限的open将自行截断文件。这一点很好@cdarke。进行了更改。它现在会截断文件,但在打开文件后不会打印文件中最初的内容。您确定文件中最初有内容吗?它对我有用。您应该只添加了一个target.seek0行,也许您添加了两种方法?是的。检查文件中是否有内容。这是我添加的唯一一行。对我来说也没什么意义/在检查文件内容之前,您是否已将脚本运行到完成状态?在刷新缓冲区之前,文件将显示为空,通常在文件关闭时。
$ 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
$