繁体   English   中英

如何在 Python 中删除 CSV 文件

[英]How to delete a CSV file in Python

我正在做一个项目,需要我添加、删除 CSV 文件中的数据,我这样做的方法是创建一个名为outfile.csv的新 CSV 文件,该文件包含来自另一个名为infile.csv CSV 文件的所有信息infile.csvoutfile.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)

Python 有一个临时文件工具,我会检查一下……但是要删除文件,您可以使用 os.remove():

import os
os.remove('outfile.csv')

要删除文件,您必须导入OS模块,并运行其os.remove()函数:

import os

os.remove("outfile.csv")

潜规则:检查文件是否存在,然后删除它

为避免出现错误,您可能需要在尝试删除文件之前检查该文件是否存在。

  • 这可以通过两种方式实现:
    • 案例1:检查文件是否存在。
    • 案例 2:使用异常处理。

情况1:

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!

案例2:

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!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM