How to erase the file contents of text file in Pyt

2020-02-07 14:50发布

I have text file which I want to erase in Python. How do I do that?

标签: python
10条回答
家丑人穷心不美
2楼-- · 2020-02-07 14:56

Not a complete answer more of an extension to ondra's answer

When using truncate() ( my preferred method ) make sure your cursor is at the required position. When a new file is opened for reading - open('FILE_NAME','r') it's cursor is at 0 by default. But if you have parsed the file within your code, make sure to point at the beginning of the file again i.e truncate(0) By default truncate() truncates the contents of a file starting from the current cusror position.

A simple example

查看更多
▲ chillily
3楼-- · 2020-02-07 15:02

Assigning the file pointer to null inside your program will just get rid of that reference to the file. The file's still there. I think the remove() function in the c stdio.h is what you're looking for there. Not sure about Python.

查看更多
成全新的幸福
4楼-- · 2020-02-07 15:04

Since text files are sequential, you can't directly erase data on them. Your options are:

  • The most common way is to create a new file. Read from the original file and write everything on the new file, except the part you want to erase. When all the file has been written, delete the old file and rename the new file so it has the original name.
  • You can also truncate and rewrite the entire file from the point you want to change onwards. Seek to point you want to change, and read the rest of file to memory. Seek back to the same point, truncate the file, and write back the contents without the part you want to erase.
  • Another simple option is to overwrite the data with another data of same length. For that, seek to the exact position and write the new data. The limitation is that it must have exact same length.

Look at the seek/truncate function/method to implement any of the ideas above. Both Python and C have those functions.

查看更多
爷、活的狠高调
5楼-- · 2020-02-07 15:07

From user @jamylak an alternative form of open("filename","w").close() is

with open('filename.txt','w'): pass
查看更多
时光不老,我们不散
6楼-- · 2020-02-07 15:09

In python:

open('file.txt', 'w').close()

Or alternatively, if you have already an opened file:

f = open('file.txt', 'r+')
f.truncate(0) # need '0' when using r+

In C++, you could use something similar.

查看更多
放荡不羁爱自由
7楼-- · 2020-02-07 15:13

You have to overwrite the file. In C++:

#include <fstream>

std::ofstream("test.txt", std::ios::out).close();
查看更多
登录 后发表回答