一文帶你搞懂Python如何解析CSV文件
一、CSV文件
逗號(hào)分隔值(Comma-Separated Values,CSV)是一種以純文本格式存儲(chǔ)表格數(shù)據(jù)的文件格式。每一行代表一條數(shù)據(jù)記錄,每條記錄由一個(gè)或多個(gè)字段組成。字段分隔符默認(rèn)使用逗號(hào)分隔,實(shí)際使用中也可以采用其他字符作為分隔符,如分號(hào) ;或制表符 \t等。
1. 基本結(jié)構(gòu)
- 每一行:表示一條數(shù)據(jù)記錄。
- 字段:記錄中的每個(gè)數(shù)據(jù)項(xiàng),用字段分隔符分隔。
- 字段值:文本或數(shù)字,可以包含特殊字符。
姓名,年齡,城市
張三,30,北京
李四,25,上海
2. 特殊情況
字段中若包含回車換行符、雙引號(hào)或者逗號(hào),該字段需要用雙引號(hào)括起來(lái)。如果用雙引號(hào)括字段,那么出現(xiàn)在字段內(nèi)的雙引號(hào)前必須加一個(gè)雙引號(hào)進(jìn)行轉(zhuǎn)義。
"aaa","b bb","ccc" "aaa","b""bb","ccc"
二、Python解析
1. 數(shù)據(jù)文件(data.csv)
id,name,age,city 1,Alice,30,New York 2,Bob,25,Los Angeles 3,Charlie,35,Chicago 4,David,40,Houston
2. 原生python
導(dǎo)入csv包之后對(duì)文件進(jìn)行解析。
import csv
# 1. 讀取 CSV 文件
with open('data.csv', mode='r', newline='', encoding='utf-8') as file:
reader = csv.reader(file)
data = list(reader)
# 2. 取行/列數(shù)據(jù)
# 取第二行數(shù)據(jù)
print("\n第二行數(shù)據(jù):", data[1])
# 取第三列數(shù)據(jù)
column_index = 2
column_data = [row[column_index] for row in data]
print("\n第三列數(shù)據(jù):", column_data)
# 3. 遍歷數(shù)據(jù)
print("\n遍歷數(shù)據(jù):")
for row in data:
print(row)
# 4. 批量修改某行/列數(shù)據(jù)
# 批量修改第二行數(shù)據(jù)
new_row_data = ['5', 'Eva', '28', 'San Francisco']
data[1] = new_row_data
# 批量修改第三列數(shù)據(jù)
new_column_data = ['31', '26', '36', '41']
for i, row in enumerate(data[1:], start=1): # Skip header row
row[column_index] = new_column_data[i - 1]
# 5. 修改某個(gè)具體的值
# 修改第一行第二列的具體值
data[0][1] = 'Alicia'
# 6. 增加某行/列數(shù)據(jù)
# 增加新行
new_row = ['5', 'Eva', '28', 'San Francisco']
data.append(new_row)
# 增加新列
new_column_data = ['USA'] * len(data) # New column data
for row, value in zip(data, new_column_data):
row.append(value)
# 7. 刪除某行/列數(shù)據(jù)
# 刪除第二行
del data[1]
# 刪除第三列
for row in data:
del row[2]
# 8. 存儲(chǔ)數(shù)據(jù)
# 保存修改后的數(shù)據(jù)
with open(file_path, mode='w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerows(data)
print("\n修改后的數(shù)據(jù):")
for row in data:
print(row)3. pandas
導(dǎo)入pandas包之后對(duì)文件進(jìn)行解析。
import pandas as pd
# 1. 讀取 CSV 文件
df = pd.read_csv('data.csv')
# 2. 取行/列數(shù)據(jù)
# 取第一行數(shù)據(jù)
print("\n第一行數(shù)據(jù):")
print(df.iloc[0])
# 取 'name' 列的數(shù)據(jù)
print("\n'name' 列的數(shù)據(jù):")
print(df['name'])
# 3. 遍歷數(shù)據(jù)
print("\n遍歷數(shù)據(jù):")
for index, row in df.iterrows():
print(f"ID: {row['id']}, Name: {row['name']}, Age: {row['age']}, City: {row['city']}")
# 4. 批量修改某行/列數(shù)據(jù)
# 修改 'age' 列中所有人的年齡,加5歲
df['age'] = df['age'] + 5
# 修改 'city' 列中 'New York' 的值為 'NYC'
df.loc[df['city'] == 'New York', 'city'] = 'NYC'
# 5. 修改某個(gè)具體的值
# 修改 ID 為 2 的人的 'age' 為 28
df.loc[df['id'] == 2, 'age'] = 28
# 刪除 'city' 列
df = df.drop(columns=['city'])
# 6. 增加行/列,并填充數(shù)據(jù)
# 增加一列 'email' 并填充默認(rèn)值 'unknown'
df['email'] = 'unknown'
# 增加一行數(shù)據(jù)
new_row = {'id': 5, 'name': 'Eve', 'age': 22, 'email': 'eve@example.com'}
df.loc[len(df)] = new_row
# 7. 刪除某行/列數(shù)據(jù)
# 刪除 ID 為 4 的行
df = df[df['id'] != 4]
# 刪除 'city' 列
df = df.drop(columns=['city'])
# 8. 存儲(chǔ)數(shù)據(jù)
df.to_csv('modified_data.csv', index=False)
print("\n修改后的數(shù)據(jù):")
print(df)to_csv函數(shù)詳解:
DataFrame.to_csv(path_or_buf=None, sep=', ', na_rep='', float_format=None,
columns=None, header=True, index=True, index_label=None, mode='w',
encoding=None, compression=None, quoting=None, quotechar='"',
line_terminator='\n', chunksize=None, tupleize_cols=None,
date_format=None, doublequote=True,escapechar=None, decimal='.')重要參數(shù):
columns: 列名sep: 字段分隔符,默認(rèn)為 ,index: 是否保存索引,默認(rèn)為 Trueheader: 是否保存列名,默認(rèn)為 Truena_rep: 替換空數(shù)據(jù)的字符串,默認(rèn)為 ‘’float_format: 設(shè)置浮點(diǎn)數(shù)的格式(保留位數(shù))path_or_buf: 文件路徑,如果沒(méi)有指定則將會(huì)直接返回字符串的 json
為了快速上手,對(duì)于CSV文件數(shù)據(jù)取出來(lái)之后的數(shù)據(jù)操作從各個(gè)方面給了簡(jiǎn)單的demo。以取列值和行值為例(特別是pandas),根據(jù)數(shù)據(jù)情況有很多種方式,其中不乏簡(jiǎn)單便捷的,可以找具體的教程進(jìn)行學(xué)習(xí)。
到此這篇關(guān)于一文帶你搞懂Python如何解析CSV文件的文章就介紹到這了,更多相關(guān)Python解析CSV文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python try except返回異常的信息字符串代碼實(shí)例
這篇文章主要介紹了python try except返回異常的信息字符串代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08
python輕量級(jí)orm框架 peewee常用功能速查詳情
Peewee是一種簡(jiǎn)單而小的ORM。它有很少的(但富有表現(xiàn)力的)概念,使它易于學(xué)習(xí)和直觀的使用,感興趣的朋友可以參考下面文章的具體內(nèi)容2021-09-09
python opencv實(shí)現(xiàn)證件照換底功能
這篇文章主要為大家詳細(xì)介紹了python opencv實(shí)現(xiàn)證件照換底功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-08-08
使用Python實(shí)現(xiàn)ELT統(tǒng)計(jì)多個(gè)服務(wù)器下所有數(shù)據(jù)表信息
這篇文章主要介紹了使用Python實(shí)現(xiàn)ELT統(tǒng)計(jì)多個(gè)服務(wù)器下所有數(shù)據(jù)表信息,ETL,是英文Extract-Transform-Load的縮寫,用來(lái)描述將數(shù)據(jù)從來(lái)源端經(jīng)過(guò)抽取(extract)、轉(zhuǎn)換(transform)、加載(load)至目的端的過(guò)程,需要的朋友可以參考下2023-07-07
對(duì)Python多線程讀寫文件加鎖的實(shí)例詳解
今天小編就為大家分享一篇對(duì)Python多線程讀寫文件加鎖的實(shí)例詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-01-01
實(shí)例講解Python設(shè)計(jì)模式編程之工廠方法模式的使用
這篇文章主要介紹了Python設(shè)計(jì)模式編程之工廠方法模式的運(yùn)用實(shí)例,文中也對(duì)Factory Method模式中涉及到的角色作出了解析,需要的朋友可以參考下2016-03-03
python獲取版本信息的方法與第三方庫(kù)總結(jié)
這篇文章主要為大家詳細(xì)介紹了python獲取版本信息的方法與第三方庫(kù),文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,感興趣的小伙伴可以了解下2025-11-11

