Python讀取和寫入txt、Excel文件和JSON文件的方法
Python 提供了多種方法來讀取和寫入不同類型的文件,包括文本文件(txt)、Excel 文件和 JSON 文件。以下是一些常用的方法和示例代碼:
讀取/寫入 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())
寫入 txt 文件
- 使用內(nèi)置的
open函數(shù)
# 寫入文本到文件(覆蓋模式)
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ù)
讀取/寫入 Excel 文件
基本讀取
讀取 Excel 文件
- 使用
pandas庫
import pandas as pd
# 讀取 Excel 文件
df = pd.read_excel('example.xlsx', sheet_name='Sheet1')
print(df)
- 使用
openpyxl庫(適用于 .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)
寫入 Excel 文件
- 使用
pandas庫
import pandas as pd
# 創(chuàng)建一個(gè) DataFrame
data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)
# 寫入 Excel 文件
df.to_excel('example.xlsx', sheet_name='Sheet1', index=False)
- 使用
openpyxl庫
from openpyxl import Workbook
# 創(chuàng)建一個(gè)新的 Excel 文件
wb = Workbook()
sheet = wb.active
sheet.title = 'Sheet1'
# 寫入數(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ù)
讀取/寫入 JSON 文件
基本讀取
基本讀取 JSON 文件
- 使用內(nèi)置的
json模塊
import json
# 讀取 JSON 文件
with open('example.json', 'r', encoding='utf-8') as file:
data = json.load(file)
print(data)
寫入 JSON 文件
- 使用內(nèi)置的
json模塊
import json
# 數(shù)據(jù)
data = {'name': 'Alice', 'age': 25}
# 寫入 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)
# 訪問嵌套數(shù)據(jù)
print(data['address']['city']) # 輸出: New York
print(data['phones'][0]) # 輸出: 123-456-7890
寫入嵌套 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"]
}
# 寫入 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í)非常有用。以下是一些方法來按行讀取 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 庫逐行解析嵌套 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 文件(分塊讀?。?/h4>
對(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 庫
jsonlines 庫專門用于處理每行一個(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)和大小選擇合適的方法來處理數(shù)據(jù)。
以上是一些常見的方法來讀取和寫入 txt、Excel 和 JSON 文件。每種方法都有其優(yōu)缺點(diǎn),選擇哪種方法取決于具體的需求和使用場景。
以上就是Python讀取和寫入txt、Excel文件和JSON文件的方法的詳細(xì)內(nèi)容,更多關(guān)于Python讀取和寫入txt、Excel和JSON的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
使用keras實(shí)現(xiàn)孿生網(wǎng)絡(luò)中的權(quán)值共享教程
這篇文章主要介紹了使用keras實(shí)現(xiàn)孿生網(wǎng)絡(luò)中的權(quán)值共享教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-06-06
Python實(shí)現(xiàn)根據(jù)Excel表格某一列內(nèi)容與數(shù)據(jù)庫進(jìn)行匹配
這篇文章主要為大家詳細(xì)介紹了Python如何使用pandas庫和Brightway2庫實(shí)現(xiàn)根據(jù)Excel表格某一列內(nèi)容與數(shù)據(jù)庫進(jìn)行匹配,需要的可以參考下2025-02-02
Python3標(biāo)準(zhǔn)庫之dbm UNIX鍵-值數(shù)據(jù)庫問題
dbm是面向DBM數(shù)據(jù)庫的一個(gè)前端,DBM數(shù)據(jù)庫使用簡單的字符串值作為鍵來訪問包含字符串的記錄。這篇文章主要介紹了Python3標(biāo)準(zhǔn)庫:dbm UNIX鍵-值數(shù)據(jù)庫的相關(guān)知識(shí),需要的朋友可以參考下2020-03-03
Python結(jié)合spaCy?進(jìn)行簡易自然語言處理
這篇文章主要為大家介紹了Python結(jié)合spaCy進(jìn)行簡易自然語言處理詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06
使用Python結(jié)合Tkinter和PyAutoGUI開發(fā)精確截圖工具
在日常工作中,截圖是一個(gè)非常常見的需求,雖然?Windows?自帶截圖工具,但有時(shí)我們需要更精確的截圖方式,比如選取特定區(qū)域、快速保存截圖并進(jìn)行預(yù)覽,本篇博客將介紹一個(gè)使用?Python?結(jié)合?Tkinter?和?PyAutoGUI?開發(fā)的精確截圖工具,需要的朋友可以參考下2025-03-03

