python如何读写csv

原创
ithorizon 7个月前 (09-30) 阅读数 57 #Python

Python中CSV文件的读写操作

Python提供了内置的函数和模块来处理CSV文件,下面介绍两种常用的方法。

方法一:使用csv模块

Python的csv模块可以帮助我们读写CSV文件,下面是一个使用csv模块读取CSV文件的例子:

import csv
读取CSV文件
with open('example.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

使用csv模块写入CSV文件的例子:

import csv
写入CSV文件
with open('example.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['Name', 'Age', 'City'])
    writer.writerow(['Alice', '28', 'New York'])
    writer.writerow(['Bob', '25', 'San Francisco'])

方法二:使用pandas库

除了csv模块,我们还可以使用pandas库来读写CSV文件,下面是一个使用pandas库读取CSV文件的例子:

import pandas as pd
读取CSV文件
df = pd.read_csv('example.csv')
print(df)

使用pandas库写入CSV文件的例子:

import pandas as pd
写入CSV文件
df = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [28, 25], 'City': ['New York', 'San Francisco']})
df.to_csv('example.csv', index=False)

需要注意的是,使用pandas库写入CSV文件时,需要指定index=False来避免将DataFrame的索引写入文件中。



热门