jus*_*tin 10 python csv module delete-row python-2.7
我正在尝试比较两个csv文件(fileA和fileB),并从fileB中删除fileB中找不到的任何行.我希望能够在不创建第三个文件的情况下执行此操作.我以为我可以使用csv编写器模块做到这一点,但现在我第二次猜测自己.
目前,我正在使用以下代码来记录文件B中的比较数据:
removal_list = set()
with open('fileB', 'rb') as file_b:
reader1 = csv.reader(file_b)
next(reader1)
for row in reader1:
removal_list.add((row[0], row[2]))
Run Code Online (Sandbox Code Playgroud)
这是我卡住的地方,不知道如何删除行:
with open('fileA', 'ab') as file_a:
with open('fileB', 'rb') as file_b:
writer = csv.writer(file_a)
reader2 = csv.reader(file_b)
next(reader2)
for row in reader2:
if (row[0], row[2]) not in removal_list:
# If row was not present in file B, Delete it from file A.
#stuck here: writer.<HowDoIRemoveRow>(row)
Run Code Online (Sandbox Code Playgroud)
此解决方案使用fileinputwith inplace=True,写入临时文件,然后自动将其重命名为文件名.您无法从文件中删除行,但只能使用您想要的行重写它.
如果将关键字参数
inplace=1传递给构造函数fileinput.input()或将其传递给FileInput构造函数,则将文件移动到备份文件,并将标准输出定向到输入文件(如果与备份文件同名的文件已存在,则将以静默方式替换) .这使得编写一个可以重写其输入文件的过滤器成为可能.
的fileA
h1,h2,h3
a,b,c
d,e,f
g,h,i
j,k,l
Run Code Online (Sandbox Code Playgroud)
FILEB
h1,h2,h3
a,b,c
1,2,3
g,h,i
4,5,6
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
的fileA
h1,h2,h3
a,b,c
g,h,i
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27828 次 |
| 最近记录: |