如果存在某个值,请删除CSV文件中的单元格 [英] Remove cell in a CSV file if a certain value is there
问题描述
我有两种类型的CSV文件,我想将它们合并在一起. 为此,我想在每一行中定位某些值,如果它们存在,则将其删除.
I have two types of CSV files, and I want to merge them together. To do that, I want to locate certain values in each row and remove them if they are there.
我尝试使用 list.Index 或 list.Remove 函数,但是当值不在特定文件中时出现错误.
I tried using list.Index or list.Remove functions but I get an error when the values are not in the specific file.
例如,这两行是(我将其余行切掉以更好地显示):
For example, the two rows are (I cut the rest of the rows for better display):
CSV 1950 1300 1180 48 48 400 2 PASS 0 51:31.5
CSV 3270 2500 1950 1300 1180 48
我想用" 3270 "和" 2500 "值定位单元格,以便两个文件对齐... 之后,我要删除空单元格,以便再次-它们将对齐...
I want to locate the cells with the values "3270" and "2500" so the two files will align... After that I want to remove the empty cells so again - they will align...
能否请您帮助我了解执行此操作的方法?
Can you please help me understand the way to do this?
谢谢, 猎人.
推荐答案
很难准确说明您希望完成什么,但是我认为这应该可以帮助您入门.
It's hard to tell exactly what you're hoping to accomplish, but I think this ought to get you started.
#!/usr/bin/env python
import csv
myfile = '/path/to/untitled.csv'
newfile = '/path/to/untitled_new.csv'
reader = csv.reader(open(myfile))
remove_me = {'3270','2500'}
print('Before:')
print(open(myfile).read())
for row in reader:
new_row = []
for column in row:
if column not in remove_me:
new_row.append(column)
csv.writer(open(newfile,'a')).writerow(new_row)
print('\n\n')
print('After:')
print(open(newfile).read())
输出:
Before:
1950,1300,1180,48,48,400
3270,2500,1950,1300,1180
After:
1950,1300,1180,48,48,400
1950,1300,1180
请确保在遍历同一列表时不使用list.remove,否则您可能会搞砸自己.上面的代码使用了一种更安全的策略,将通过if
测试(列是 not 您要删除的值之一)的值复制到新列表中,然后编写新的列出一个新的.csv文件.
Make sure that you're not using list.remove while you're iterating over that same list, or you'll likely mess yourself up. My code above uses a safer strategy of copying the values that pass your if
test (column is not one of your values that you want to get rid of) to a new list, then writing that new list to a new .csv file.
这或多或少是您打算做什么?
Is this more or less what you're intending to do?
要摆脱空白单元格,我想您可以将''
添加到remove_me
.
To get rid of blank cells, I presume you could add ''
to remove_me
.
这篇关于如果存在某个值,请删除CSV文件中的单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!