我正在做一个项目,要求我添加,删除CSV文件中的数据,我这样做的方法是创建一个名为outfile.csv
的新CSV文件,其中包含来自的所有信息另一个名为infile.csv
的CSV文件(outfile.csv
有一些我删除的行),因此outfile.csv
基本上是一个临时文件。
无论如何我可以删除CSV文件(我已经看到了一些像这样的问题,但是所有答案都只是截断 CSV文件)?
这是我的代码:
__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)
答案 0 :(得分:9)
Python有一个tempfile工具我会检查出来...... 但要删除文件,请使用os.remove():
import os
os.remove('outfile.csv')
答案 1 :(得分:0)
要删除文件,您必须导入 OS
模块,并运行其 os.remove()
函数:
import os
os.remove("outfile.csv")
为避免出现错误,您可能需要在尝试删除文件之前检查该文件是否存在。
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))
输出:
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))
输出:
# 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!