方法一:
使用python自带的csv模块
1.导入
import csv
2.获取文本数据
with open('result.csv', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
print(row)
3.获取每一列的数据
username = row['username']
4.完整代码
import csv
with open('文件名.csv',encoding='utf-8') as f:
reader=csv.DictReader(f)
for row in reader:
print(row)
name=row[1]#第一列数据
print(f"用户名{name}")
方法二:使用pandas--read_csv()
1.读取文件
import pandas as pd
# 读取CSV文件
df = pd.read_csv('data.csv')
print(df.head())
2.缺失值处理
# 处理缺失值
df = pd.read_csv('data.csv', na_values=['NA', '?'])
3.指定列名
# 指定列名
df = pd.read_csv('data.csv', names=['A', 'B', 'C'])
4.
# 分块读取大文件
chunk_size = 10000
for chunk in pd.read_csv('data.csv', chunksize=chunk_size):
process(chunk) # 处理每个数据块