Reputation: 625
how can I clear a complete csv file with python. Most forum entries that cover the issue of deleting row/columns basically say, write the stuff you want to keep into a new file. I need to completely clear a file - how can I do that?
Upvotes: 11
Views: 61028
Reputation: 294
Basically you want to truncate the file, this can be any file. In this case it's a csv file so:
filename = "filewithcontents.csv"
# opening the file with w+ mode truncates the file
f = open(filename, "w+")
f.close()
Upvotes: 28
Reputation: 17138
Your question is rather strange, but I'll interpret it literally. Clearing a file is not the same as deleting it.
You want to open a file
object to the CSV file, and then truncate
the file, bringing it to zero length.
f = open("filename.csv", "w")
f.truncate()
f.close()
If you want to delete it instead, that's just a os filesystem call:
import os
os.remove("filename.csv")
Upvotes: 16
Reputation:
The Python csv module is only for reading and writing whole CSV files but not for manipulating them. If you need to filter data from file then you have to read it, create a new csv file and write the filtered rows back to new file.
Upvotes: 1