如何在Python中删除CSV文件 [英] How to delete a CSV file in Python
问题描述
我正在做一个项目,需要我添加,删除CSV文件中的数据,而我要做的方法是创建一个名为 outfile.csv $的新CSV文件。 c $ c>包含另一个CSV文件的所有信息,该文件称为
infile.csv
( outfile.csv
行,因此 outfile.csv
基本上是一个临时文件。
无论如何我都可以删除
这是我的CSV文件(我已经看到了一些类似的问题,但所有答案都只是说截断 CSV文件)?
代码:
__ row_num1 = __row_num.get()
FIRST_ROW_NUM = 1
rows_to_delete = {__row_num1}
,其中open( ./ user_info / +用户名+ .csv, rt)作为文件名,open('outfile.csv','wt')作为文件名:
outfile.writelines(行为row_num,行为枚举(infile,FIRST_ROW_NUM),如果row_num不位于rows_to_delete中)
infile.close()
outfile.close()
USER_INFO_FILE = open( outfile.csv)
outfile_dict = []
read_file = csv.reader(USER_INFO_FILE)
在read_file中的行:
outfile_dict.append(row)
USER_INFO_FILE.close
f = open( ./ user_info / +用户名+ .csv, w)
f.truncate()
f.close
writer = csv.writer(open( ./ user_info / +用户名+ .csv, ab),定界符=',')
writer.writerows(outfile_dict)
Python的 tempfile 工具我会检查一下...
但要删除一个您使用的文件os.remove():
import os
os.remove('outfile.csv')
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.
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)?
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)
Python has a tempfile facility I would check that out... But to remove a file you use os.remove():
import os
os.remove('outfile.csv')
这篇关于如何在Python中删除CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!