如何从CSV fi中删除具有特定值的单元格

2024-09-30 05:23:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个csv文件,在最后一行有一个单元格。我需要找到一个删除。e、 g

Total1254612

total的值不会一直都是相同的,这是导致问题的原因。在


Tags: 文件csv原因totaltotal1254612
3条回答

This is iterating through the main file & write to a new file without the cell 'Total'

f_original = open(fname, 'r')
f_new = open(fname+'_new.csv', 'w')

#iterate through the lines
for line in f_original:
    if not line.startswith('Total'):
        f_new.write(line)

f_original.close()
f_new.close()

Thanks Lucas & Wilbur

您还可以使用pandas

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({
        'A' : [1,2,3,4],
        'B' : ['a','b','c','d'],
        })
In [3]: df.head()

           A  B
        0  1  a
        1  2  b
        2  3  c
        3  4  d
In [4]: df.drop(df.index[len(df)-1])

           A  B
        0  1  a
        1  2  b
        2  3  c

您可以利用这样一个事实:您知道只有一个值,并且前5个字母是'Total'。我只需将不满足这些条件的所有行重写为新文件:

f_original = open(fname, 'r')
f_new = open(fname+'_new.csv', 'w')

#iterate through the lines
for line in f_original:
    if line.startswith('Total'):
        f_new.write(line)

f_original.close()
f_new.close()

相关问题 更多 >

    热门问题