使用Python删除CSV文件中的特定行

2 投票
1 回答
10511 浏览
提问于 2025-04-16 01:09

我想从下面这个csv文件中删除特定的行:

"Title.XP PoseRank" 

1VDV-constatomGlu-final-NoGluWat. 

1VDV-constatomGlu-final-NoGluWat. 

P6470-Usha.1 

P6470-Usha.2 

P6470-Usha.3 

P6470-Usha.4 

P6470-Usha.5 

P6515-Usha.1 

P6515-Usha.2 

P6517.1 

P6517.2 

P6517.3 

P6517.4 

P6517.5 

P6553-Usha.1 

P6553-Usha.2 

P6553-Usha.3 

我想删除那些以 1VDV-constatomGlu-final-NoGluWat. 开头的行。

1 个回答

2

正确的解决办法是使用 CSV 解析器(我没有测试这段代码):


writer = csv.writer(open('corrected.csv'))
for row in csv.reader('myfile.csv'):
    if not row[0].startswith('1VDV-constatomGlu-final-NoGluWat.'):
        writer.writerow(row)
writer.close()

你也可以使用正则表达式或者一些字符串处理的方法,但这样做有风险,因为经过这些处理后,文件可能就不再是 CSV 格式了。

撰写回答