[英]How to delete a CSV file in Python
I'm doing a project which requires me to add, delete data that is in a CSV file, the way I have done it is by creating a new CSV file called outfile.csv
, which holds all the information from another CSV file called infile.csv
( outfile.csv
has some rows which I deleted), so outfile.csv
is basically a temp file.我正在做一个项目,需要我添加、删除 CSV 文件中的数据,我这样做的方法是创建一个名为outfile.csv
的新 CSV 文件,该文件包含来自另一个名为infile.csv
CSV 文件的所有信息infile.csv
( outfile.csv
有一些我删除的行),所以outfile.csv
基本上是一个临时文件。
Is there anyway I could delete the CSV file (I've seen a few questions like these but all the answers say to just truncate the CSV file)?无论如何我可以删除 CSV 文件(我已经看到了一些这样的问题,但所有的答案都说只是截断CSV 文件)?
Here's my code:这是我的代码:
__row_num1 = __row_num.get()
FIRST_ROW_NUM = 1
rows_to_delete = {__row_num1}
with open("./user_info/" + Username + ".csv", "rt") as infile, open('outfile.csv', 'wt') as outfile:
outfile.writelines(row for row_num, row in enumerate(infile, FIRST_ROW_NUM)if row_num not in rows_to_delete)
infile.close()
outfile.close()
USER_INFO_FILE = open("outfile.csv")
outfile_dict = []
read_file = csv.reader(USER_INFO_FILE)
for row in read_file:
outfile_dict.append(row)
USER_INFO_FILE.close
f = open("./user_info/" + Username + ".csv", "w")
f.truncate()
f.close
writer = csv.writer(open("./user_info/" + Username + ".csv", "ab"), delimiter=',')
writer.writerows(outfile_dict)
To delete a file, you must import the OS
module, and run its os.remove()
function:要删除文件,您必须导入OS
模块,并运行其os.remove()
函数:
import os
os.remove("outfile.csv")
To avoid getting an error, you might want to check if the file exists before you try to delete it.为避免出现错误,您可能需要在尝试删除文件之前检查该文件是否存在。
import os
my_file="/path/to/outfile.csv"
# check if file exists
if os.path.exists(my_file):
os.remove(my_file)
# Print the statement once the file is deleted
print("The file: {} is deleted!".format(my_file))
else:
print("The file: {} does not exist!".format(my_file))
output:输出:
The file: /path/to/outfile.csv is deleted!
# or
The file: /path/to/outfile.csv does not exist!
import os
my_file="/path/to/outfile.csv"
## Try to delete the file
try:
os.remove(my_file)
print("The file: {} is deleted!".format(my_file))
except OSError as e:
print("Error: {} - {}!".format(e.filename, e.strerror))
output:输出:
# example of an error
Error: /path/to/outfile.csv - No such file or directory!
Error: /path/to/outfile.csv - Operation not permitted!
# successfully
The file: /path/to/outfile.csv is deleted!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.