【问题标题】:How to remove a specific row from a CSV file in Python如何从 Python 中的 CSV 文件中删除特定行
【发布时间】:2023-02-07 21:10:47
【问题描述】:

如何从 CSV 中删除一行?

user1,user2
user2,user3

我有这个 csv 文件,我只需要删除第一行。

import csv

with open("info.csv", "w") as file:
 for line in file:
     f.writerow(line)

【问题讨论】:

标签: python


【解决方案1】:

一般来说,你不能。相反,您创建了一个跳过该行的新文件。

import csv

with open("info.csv", "r") as read_file, open("info2.csv", "w") as write_file:
    reader = csv.reader(read_file)
    writer = csv.writer(write_file)
    next(reader)  # Skip the first row
    for row in reader:
        writer.writerow(row)

【讨论】:

    【解决方案2】:
    import pandas as pd
    
    df = pd.read_csv('info.csv') 
    df = df.iloc[1: , :] # Drop first row
    df.to_csv('info.csv')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-07
      • 2020-03-05
      • 1970-01-01
      相关资源
      最近更新 更多