python怎么處理csv數(shù)據(jù)

小億
91
2024-02-01 11:55:37
欄目: 編程語言

使用Python處理CSV數(shù)據(jù)可以通過使用csv模塊來讀取、寫入和操作CSV文件。以下是一些常用的處理CSV數(shù)據(jù)的方法:

  1. 讀取CSV文件:

    import csv
    
    with open('data.csv', 'r') as file:
        csv_reader = csv.reader(file)
        for row in csv_reader:
            print(row)
    
  2. 寫入CSV文件:

    import csv
    
    data = [['Name', 'Age'], ['John', 25], ['Jane', 30], ['Tom', 35]]
    
    with open('data.csv', 'w', newline='') as file:
        csv_writer = csv.writer(file)
        csv_writer.writerows(data)
    
  3. 讀取CSV文件并將數(shù)據(jù)存儲(chǔ)為字典:

    import csv
    
    with open('data.csv', 'r') as file:
        csv_reader = csv.DictReader(file)
        for row in csv_reader:
            print(row)
    
  4. 寫入字典數(shù)據(jù)到CSV文件:

    import csv
    
    data = [{'Name': 'John', 'Age': 25}, {'Name': 'Jane', 'Age': 30}, {'Name': 'Tom', 'Age': 35}]
    fieldnames = ['Name', 'Age']
    
    with open('data.csv', 'w', newline='') as file:
        csv_writer = csv.DictWriter(file, fieldnames=fieldnames)
        csv_writer.writeheader()
        csv_writer.writerows(data)
    
  5. 對(duì)CSV數(shù)據(jù)進(jìn)行排序:

    import csv
    
    with open('data.csv', 'r') as file:
        csv_reader = csv.reader(file)
        sorted_rows = sorted(csv_reader, key=lambda row: row[1])  # 根據(jù)第二列進(jìn)行排序
        
        for row in sorted_rows:
            print(row)
    
  6. 過濾CSV數(shù)據(jù):

    import csv
    
    with open('data.csv', 'r') as file:
        csv_reader = csv.reader(file)
        filtered_rows = filter(lambda row: int(row[1]) > 25, csv_reader)  # 過濾年齡大于25的行
        
        for row in filtered_rows:
            print(row)
    

這些是一些基本的CSV數(shù)據(jù)處理方法,可以根據(jù)具體需求進(jìn)行靈活運(yùn)用。

0