gpt4 book ai didi

python - 如何删除 csv 文件中的整行并将更改保存在同一文件中?

转载 作者:太空宇宙 更新时间:2023-11-04 10:08:12 25 4
gpt4 key购买 nike

我是 python 的新手,尝试修改 csv 文件,这样我就可以根据给定的列表删除具有特定字段的特定行。在我当前的代码中,我得到了我想要删除的行,但我无法删除它并将更改保存在同一个文件中(替换)。

 import os, sys, glob
import time ,csv
# Open a file
path = 'C:\\Users\\tzahi.k\\Desktop\\netzer\\'
dirs = os.listdir( path )
fileslst = []
alertsCode = ("42001", "42003", "42006","51001" , "51002" ,"61001" ,"61002","71001",
"71002","71003","71004","71005","71006","72001","72002","72003","72004",
"82001","82002","82003","82004","82005","82006","82007","83001","84001")
# This would print the unnesscery codes
for file in dirs:
if "ALERTS" in file.upper() :
fileslst.append(file)
fileslst.sort()

with open(fileslst[-1], 'rb') as csvfile:
csvReader = csv.reader(csvfile)
for row in csvReader:
for alert in alertsCode:
if any(alert in row[2] for s in alertsCode) :
print row

有什么帮助吗?

最佳答案

使用列表理解 将所有行读入列表并排除不需要的行。然后以 w 模式(写入模式)将行重写到文件中,这会覆盖或替换文件的内容:

with open(fileslst[-1], 'rb') as csvfile:
csvReader = csv.reader(csvfile)
clean_rows = [row for row in csvReader if not any(alert in row[2] for alert in alertsCode)]
# csvfile.truncate()

with open(fileslst[-1], 'wb') as csvfile:
csv_writer = csv.writer(csvfile)
csv_writer.writerows(clean_rows)

关于python - 如何删除 csv 文件中的整行并将更改保存在同一文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39769041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com