Python讀取和寫(xiě)入txt、Excel文件和JSON文件的方法
Python 提供了多種方法來(lái)讀取和寫(xiě)入不同類型的文件,包括文本文件(txt)、Excel 文件和 JSON 文件。以下是一些常用的方法和示例代碼:
讀取/寫(xiě)入 txt 文件
基本讀取txt
讀取 txt 文件
- 使用內(nèi)置的
open函數(shù)
# 讀取整個(gè)文件內(nèi)容
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
# 逐行讀取文件內(nèi)容
with open('example.txt', 'r', encoding='utf-8') as file:
for line in file:
print(line.strip())
寫(xiě)入 txt 文件
- 使用內(nèi)置的
open函數(shù)
# 寫(xiě)入文本到文件(覆蓋模式)
with open('example.txt', 'w', encoding='utf-8') as file:
file.write('Hello, World!\n')
# 追加文本到文件
with open('example.txt', 'a', encoding='utf-8') as file:
file.write('Appending a new line.\n')
按行讀取復(fù)雜數(shù)據(jù)
- 逐行讀取并處理每行數(shù)據(jù)
# 假設(shè)我們的文件內(nèi)容如下:
# Name, Age, City
# Alice, 30, New York
# Bob, 25, Los Angeles
with open('example.txt', 'r', encoding='utf-8') as file:
header = file.readline().strip().split(', ')
data = []
for line in file:
values = line.strip().split(', ')
record = dict(zip(header, values))
data.append(record)
print(data)
處理大txt文本文件(逐行讀取以節(jié)省內(nèi)存)
# 逐行讀取大文件
with open('large_file.txt', 'r', encoding='utf-8') as file:
for line in file:
process_line(line) # 自定義的處理函數(shù)
讀取/寫(xiě)入 Excel 文件
基本讀取
讀取 Excel 文件
- 使用
pandas庫(kù)
import pandas as pd
# 讀取 Excel 文件
df = pd.read_excel('example.xlsx', sheet_name='Sheet1')
print(df)
- 使用
openpyxl庫(kù)(適用于 .xlsx 文件)
from openpyxl import load_workbook
# 讀取 Excel 文件
wb = load_workbook('example.xlsx')
sheet = wb['Sheet1']
for row in sheet.iter_rows(values_only=True):
print(row)
寫(xiě)入 Excel 文件
- 使用
pandas庫(kù)
import pandas as pd
# 創(chuàng)建一個(gè) DataFrame
data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)
# 寫(xiě)入 Excel 文件
df.to_excel('example.xlsx', sheet_name='Sheet1', index=False)
- 使用
openpyxl庫(kù)
from openpyxl import Workbook
# 創(chuàng)建一個(gè)新的 Excel 文件
wb = Workbook()
sheet = wb.active
sheet.title = 'Sheet1'
# 寫(xiě)入數(shù)據(jù)
sheet.append(['Name', 'Age'])
sheet.append(['Alice', 25])
sheet.append(['Bob', 30])
# 保存文件
wb.save('example.xlsx')
處理復(fù)雜 Excel 文件(多個(gè)工作表)
- 使用
pandas讀取多個(gè)工作表
import pandas as pd
# 讀取 Excel 文件的所有工作表
xls = pd.ExcelFile('example.xlsx')
sheets = {}
for sheet_name in xls.sheet_names:
sheets[sheet_name] = pd.read_excel(xls, sheet_name=sheet_name)
print(f"Sheet: {sheet_name}")
print(sheets[sheet_name])
- 使用
openpyxl逐行讀取
from openpyxl import load_workbook
# 讀取 Excel 文件
wb = load_workbook('example.xlsx')
for sheet_name in wb.sheetnames:
sheet = wb[sheet_name]
print(f"Sheet: {sheet_name}")
for row in sheet.iter_rows(values_only=True):
print(row)
處理大 Excel 文件(使用 pandas 的 chunksize 參數(shù))
import pandas as pd
# 逐塊讀取大 Excel 文件
chunk_size = 1000
for chunk in pd.read_excel('large_file.xlsx', sheet_name='Sheet1', chunksize=chunk_size):
process_chunk(chunk) # 自定義的處理函數(shù)
讀取/寫(xiě)入 JSON 文件
基本讀取
基本讀取 JSON 文件
- 使用內(nèi)置的
json模塊
import json
# 讀取 JSON 文件
with open('example.json', 'r', encoding='utf-8') as file:
data = json.load(file)
print(data)
寫(xiě)入 JSON 文件
- 使用內(nèi)置的
json模塊
import json
# 數(shù)據(jù)
data = {'name': 'Alice', 'age': 25}
# 寫(xiě)入 JSON 文件
with open('example.json', 'w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=4)
讀取嵌套數(shù)據(jù):
讀取嵌套json文件:
- 讀取嵌套 JSON 數(shù)據(jù)
import json
# 假設(shè)我們的 JSON 文件內(nèi)容如下:
# {
# "name": "Alice",
# "age": 30,
# "address": {
# "city": "New York",
# "zipcode": "10001"
# },
# "phones": ["123-456-7890", "987-654-3210"]
# }
with open('example.json', 'r', encoding='utf-8') as file:
data = json.load(file)
print(data)
# 訪問(wèn)嵌套數(shù)據(jù)
print(data['address']['city']) # 輸出: New York
print(data['phones'][0]) # 輸出: 123-456-7890
寫(xiě)入嵌套 JSON 數(shù)據(jù)
import json
# 嵌套數(shù)據(jù)
data = {
"name": "Alice",
"age": 30,
"address": {
"city": "New York",
"zipcode": "10001"
},
"phones": ["123-456-7890", "987-654-3210"]
}
# 寫(xiě)入 JSON 文件
with open('example.json', 'w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=4)
復(fù)雜讀取json文件
按行讀取 JSON 文件在處理大文件或流式處理數(shù)據(jù)時(shí)非常有用。以下是一些方法來(lái)按行讀取 JSON 文件:
方法一:逐行讀取并解析每行 JSON
如果 JSON 文件每行都是一個(gè)獨(dú)立的 JSON 對(duì)象,可以逐行讀取并解析每行:
import json
# 假設(shè)我們的 JSON 文件內(nèi)容如下,每行是一個(gè)獨(dú)立的 JSON 對(duì)象:
# {"name": "Alice", "age": 30}
# {"name": "Bob", "age": 25}
with open('example.json', 'r', encoding='utf-8') as file:
for line in file:
data = json.loads(line.strip())
print(data)
方法二:逐行讀取并解析嵌套 JSON
如果 JSON 文件是一個(gè)包含多個(gè)對(duì)象的數(shù)組,可以使用 ijson 庫(kù)逐行解析嵌套 JSON 數(shù)據(jù):
import ijson
# 假設(shè)我們的 JSON 文件內(nèi)容如下:
# [
# {"name": "Alice", "age": 30},
# {"name": "Bob", "age": 25}
# ]
with open('example.json', 'r', encoding='utf-8') as file:
parser = ijson.parse(file)
for prefix, event, value in parser:
if prefix.endswith('.name') and event == 'string':
print(f"Name: {value}")
elif prefix.endswith('.age') and event == 'number':
print(f"Age: {value}")
方法三:處理大 JSON 文件(分塊讀取)
對(duì)于非常大的 JSON 文件,可以考慮分塊讀取和處理:
import json
def process_chunk(chunk):
for line in chunk:
data = json.loads(line.strip())
print(data)
chunk_size = 1000 # 每次讀取1000行
with open('large_file.json', 'r', encoding='utf-8') as file:
chunk = []
for line in file:
chunk.append(line)
if len(chunk) >= chunk_size:
process_chunk(chunk)
chunk = []
if chunk:
process_chunk(chunk)
方法四:使用 jsonlines 庫(kù)
jsonlines 庫(kù)專門(mén)用于處理每行一個(gè) JSON 對(duì)象的文件:
import jsonlines
# 假設(shè)我們的 JSON 文件內(nèi)容如下,每行是一個(gè)獨(dú)立的 JSON 對(duì)象:
# {"name": "Alice", "age": 30}
# {"name": "Bob", "age": 25}
with jsonlines.open('example.json') as reader:
for obj in reader:
print(obj)
這些方法可以幫助你按行讀取 JSON 文件,根據(jù)文件的具體結(jié)構(gòu)和大小選擇合適的方法來(lái)處理數(shù)據(jù)。
以上是一些常見(jiàn)的方法來(lái)讀取和寫(xiě)入 txt、Excel 和 JSON 文件。每種方法都有其優(yōu)缺點(diǎn),選擇哪種方法取決于具體的需求和使用場(chǎng)景。
以上就是Python讀取和寫(xiě)入txt、Excel文件和JSON文件的方法的詳細(xì)內(nèi)容,更多關(guān)于Python讀取和寫(xiě)入txt、Excel和JSON的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- C++利用jsoncpp庫(kù)實(shí)現(xiàn)寫(xiě)入和讀取json文件
- C#實(shí)現(xiàn)讀取寫(xiě)入Json文件
- Python如何讀取、寫(xiě)入JSON數(shù)據(jù)
- python3 循環(huán)讀取excel文件并寫(xiě)入json操作
- Node.js fs模塊(文件模塊)創(chuàng)建、刪除目錄(文件)讀取寫(xiě)入文件流的方法
- Node.js readline 逐行讀取、寫(xiě)入文件內(nèi)容的示例
- Python讀取Json字典寫(xiě)入Excel表格的方法
- Javascript寫(xiě)入txt和讀取txt文件示例
- JavaScript?讀取及寫(xiě)入本地文件的操作方法
相關(guān)文章
詳解如何使用python實(shí)現(xiàn)猜數(shù)字游戲
“猜數(shù)字”游戲是一款簡(jiǎn)單而有趣的小游戲,玩家需要在給定的范圍內(nèi)猜出一個(gè)由計(jì)算機(jī)隨機(jī)生成的數(shù)字,本文將使用Python語(yǔ)言來(lái)實(shí)現(xiàn)這款游戲,并詳細(xì)介紹其實(shí)現(xiàn)過(guò)程,文中有詳細(xì)的代碼示例供大家參考,需要的朋友可以參考下2024-04-04
MySQL最常見(jiàn)的操作語(yǔ)句小結(jié)
這篇文章主要介紹了MySQL最常見(jiàn)的操作語(yǔ)句小結(jié),與表和庫(kù)相關(guān)的這些語(yǔ)句是學(xué)習(xí)MySQL中最基礎(chǔ)的知識(shí),需要的朋友可以參考下2015-05-05
關(guān)于python導(dǎo)入模塊import與常見(jiàn)的模塊詳解
今天小編就為大家分享一篇關(guān)于python導(dǎo)入模塊import與常見(jiàn)的模塊詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-08-08
Ubuntu環(huán)境下玩轉(zhuǎn)Python配置的實(shí)戰(zhàn)開(kāi)發(fā)全指南
本文將從基礎(chǔ)環(huán)境配置出發(fā),逐步深入到 Python 開(kāi)發(fā)的核心場(chǎng)景,幫助開(kāi)發(fā)者在 Ubuntu 系統(tǒng)中快速搭建穩(wěn)定、高效的 Python 開(kāi)發(fā)環(huán)境,并通過(guò)實(shí)戰(zhàn)案例掌握關(guān)鍵開(kāi)發(fā)技能2026-01-01
Python時(shí)間處理模塊Time和DateTime
這篇文章主要為大家介紹了Python時(shí)間處理模塊Time和DateTime使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
Python實(shí)現(xiàn)學(xué)校管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)學(xué)校管理系統(tǒng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01
如何使用五行Python代碼輕松實(shí)現(xiàn)批量摳圖
簡(jiǎn)單來(lái)說(shuō),摳圖就是將照片的主體人或物品從圖片中摳出來(lái),以便貼到別處使用,下面這篇文章主要給大家介紹了關(guān)于如何使用五行Python代碼輕松實(shí)現(xiàn)批量摳圖的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-04-04
Python使用Selenium時(shí)遇到網(wǎng)頁(yè)<body>劃不動(dòng)的問(wèn)題解決方法
如果在使用 Selenium 時(shí)遇到網(wǎng)頁(yè)的 <body> 劃不動(dòng)的問(wèn)題,這通常是因?yàn)轫?yè)面的滾動(dòng)機(jī)制(例如,可能使用了一個(gè)具有固定高度的容器或自定義的滾動(dòng)條)導(dǎo)致無(wú)法通過(guò)簡(jiǎn)單的 JavaScript 實(shí)現(xiàn)滾動(dòng),可以通過(guò)以下方法來(lái)解決該問(wèn)題2024-10-10

