您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在python中删除行CSV

如何在python中删除行CSV

解决方案使用fileinputwithinplace=True,它会写入一个临时文件,然后在最后自动将其重命名为您的文件名。您无法从文件删除 行,但只能用所需的行重写它。

如果将关键字参数inplace=1传递给构造函数fileinput.input()或将其传递给FileInput构造函数,则该文件将移动到备份文件,并且标准输出将定向到输入文件(如果已经存在与备份文件同名的文件,它将被无提示替换) 。这样就可以编写一个过滤器,该过滤器可以在适当位置重写其输入文件

文件A

h1,h2,h3
a,b,c
d,e,f
g,h,i
j,k,l

文件B

h1,h2,h3
a,b,c
1,2,3
g,h,i
4,5,6
import fileinput, sys, csv

with open('fileB', 'rb') as file_b:
    r = csv.reader(file_b)
    next(r) #skip header
    seen = {(row[0], row[2]) for row in r}

f = fileinput.input('fileA', inplace=True) # sys.stdout is redirected to the file
print next(f), # write header as first line

w = csv.writer(sys.stdout) 
for row in csv.reader(f):
   if (row[0], row[2]) in seen: # write it if it's in B
       w.writerow(row)

文件A

h1,h2,h3
a,b,c    
g,h,i
python 2022/1/1 18:35:28 有227人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶