Python 读取和写入文件的方法【文本文件(txt),Excel 文件,JSON 文件,pth文件,npy文件】
python 文本文件 excel文件 json文件 pth文件 npy文件 读取 写入
Python 读取和写入文本文件(txt)、Excel 文件和 JSON 文件的基本方法
Python 提供了多种方法来读取和写入不同类型的文件,包括文本文件(txt)、Excel 文件和 JSON 文件。以下是一些常用的方法和示例代码:
读取/写入 txt 文件
基本读取txt
读取 txt 文件
- 使用内置的
open
函数
# 读取整个文件内容
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
# 逐行读取文件内容
with open('example.txt', 'r', encoding='utf-8') as file:
for line in file:
print(line.strip())
写入 txt 文件
- 使用内置的
open
函数
# 写入文本到文件(覆盖模式)
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')
按行读取复杂数据
- 逐行读取并处理每行数据
# 假设我们的文件内容如下:
# 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文本文件(逐行读取以节省内存)
# 逐行读取大文件
with open('large_file.txt', 'r', encoding='utf-8') as file:
for line in file:
process_line(line) # 自定义的处理函数
读取/写入 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
# 创建一个 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
# 创建一个新的 Excel 文件
wb = Workbook()
sheet = wb.active
sheet.title = 'Sheet1'
# 写入数据
sheet.append(['Name', 'Age'])
sheet.append(['Alice', 25])
sheet.append(['Bob', 30])
# 保存文件
wb.save('example.xlsx')
处理复杂 Excel 文件(多个工作表)
- 使用
pandas
读取多个工作表
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
参数)
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) # 自定义的处理函数
读取/写入 JSON 文件
基本读取
基本读取 JSON 文件
- 使用内置的
json
模块
import json
# 读取 JSON 文件
with open('example.json', 'r', encoding='utf-8') as file:
data = json.load(file)
print(data)
写入 JSON 文件
- 使用内置的
json
模块
import json
# 数据
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)
读取嵌套数据:
读取嵌套json文件:
- 读取嵌套 JSON 数据
import json
# 假设我们的 JSON 文件内容如下:
# {
# "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)
# 访问嵌套数据
print(data['address']['city']) # 输出: New York
print(data['phones'][0]) # 输出: 123-456-7890
写入嵌套 JSON 数据
import json
# 嵌套数据
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)
复杂读取json文件
按行读取 JSON 文件在处理大文件或流式处理数据时非常有用。以下是一些方法来按行读取 JSON 文件:
方法一:逐行读取并解析每行 JSON
如果 JSON 文件每行都是一个独立的 JSON 对象,可以逐行读取并解析每行:
import json
# 假设我们的 JSON 文件内容如下,每行是一个独立的 JSON 对象:
# {"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 文件是一个包含多个对象的数组,可以使用 ijson
库逐行解析嵌套 JSON 数据:
import ijson
# 假设我们的 JSON 文件内容如下:
# [
# {"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 文件(分块读取)
对于非常大的 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
库专门用于处理每行一个 JSON 对象的文件:
import jsonlines
# 假设我们的 JSON 文件内容如下,每行是一个独立的 JSON 对象:
# {"name": "Alice", "age": 30}
# {"name": "Bob", "age": 25}
with jsonlines.open('example.json') as reader:
for obj in reader:
print(obj)
这些方法可以帮助你按行读取 JSON 文件,根据文件的具体结构和大小选择合适的方法来处理数据。
读取/写入 pth 文件
方法一:使用pytorch来读取和写入pth文件
-
首先进入pytorch官网安装pytorch。
如果本地电脑,没有安装gpu,可以安装cpu版本的pytorch。 -
读取和写入 .pth 文件
.pth 文件通常用于保存和加载PyTorch模型的权重或整个模型。我们可以使用 torch.save 和 torch.load 来处理这些文件。
简单情况:
例子1:比如读取一个数据文件并分析
import torch
# 指定文件路径
file_path = 'C:\\code\\relation_detection_knowledge\\vg\\des_prompts.pth'
# 加载文件
data = torch.load(file_path)
# 打印数据以查看其结构
print(data)
例子2:读取模型文件并分析
import torch
'''
*************************************************************
************************读取pth文件***************************
*************************************************************
'''
# 加载整个模型
model = torch.load('model.pth')
# 加载模型的一部分
model_dict = torch.load('model.pth')
model.load_state_dict(model_dict)
'''
*************************************************************
************************写入pth文件***************************
*************************************************************
'''
torch.save(model, 'model.pth')
复杂情况
例子1: 定义一个模型后保存或加载
import torch
import torch.nn as nn
# 定义一个简单的模型
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.fc = nn.Linear(10, 1)
def forward(self, x):
return self.fc(x)
# 实例化模型
model = SimpleModel()
# 保存模型权重
torch.save(model.state_dict(), 'model_weights.pth')
# 加载模型权重
model = SimpleModel() # 重新实例化模型
model.load_state_dict(torch.load('model_weights.pth'))
'''或者直接加载模型'''
# 加载整个模型
model = torch.load('entire_model.pth')
# 保存整个模型
torch.save(model, 'entire_model.pth')
例子2:创建一个复杂数据结构并保存成pth
import torch
# 创建一个复杂的数据结构
data = {
'array1': torch.tensor([1, 2, 3]),
'array2': torch.tensor([4, 5, 6]),
'metadata': 'example'
}
# 保存数据结构
torch.save(data, 'complex_data.pth')
# 加载数据结构
loaded_data = torch.load('complex_data.pth')
print(loaded_data)
方法二,使用site读取和写入pth文件(用于读取第三方目录)
site介绍
site
模块是 Python 标准库的一部分,主要用于配置 Python 运行环境。它会在 Python 启动时自动加载,并且可以用于操作 site-packages
目录、添加新的路径到模块搜索路径等。尽管 site
模块本身并不直接用于读取和写入 .pth
文件,但 .pth
文件在 site-packages
目录中有着特殊的用途。
site
模块的基本功能
site
模块主要提供以下功能:
- 自动加载目录:在启动时,
site
模块会自动将一些目录添加到sys.path
,以便 Python 可以找到更多的模块。 - 处理
.pth
文件:.pth
文件可以包含额外的路径,这些路径会被添加到sys.path
,从而扩展模块搜索路径。 - 自定义启动脚本:可以在
.pth
文件中包含 Python 代码,这些代码会在启动时执行。
.pth
文件的作用
.pth
文件通常位于 site-packages
目录中,它们的主要作用是向 sys.path
添加额外的目录。这对于安装第三方库非常有用。
示例 .pth
文件内容
# This is a comment
/absolute/path/to/directory
relative/path/to/directory
import sys; sys.path.append('/another/path')
使用 site
模块读取 .pth
文件
虽然 site
模块本身没有直接的 API 用于读取 .pth
文件,但我们可以手动读取这些文件并解析它们。
读取 .pth
文件的示例
import os
def read_pth_file(pth_file):
with open(pth_file, 'r') as file:
lines = file.readlines()
paths = []
for line in lines:
line = line.strip()
if line and not line.startswith('#'):
if line.startswith('import'):
exec(line)
else:
paths.append(line)
return paths
# 示例:读取一个 .pth 文件
pth_file_path = '/path/to/your/file.pth'
paths = read_pth_file(pth_file_path)
print(paths)
使用 site
模块写入 .pth
文件
写入 .pth
文件相对简单,只需将路径写入文件即可。
写入 .pth
文件的示例
def write_pth_file(pth_file, paths):
with open(pth_file, 'w') as file:
for path in paths:
file.write(path + '\n')
# 示例:写入一个 .pth 文件
pth_file_path = '/path/to/your/file.pth'
paths_to_write = [
'/absolute/path/to/directory',
'relative/path/to/directory',
'import sys; sys.path.append("/another/path")'
]
write_pth_file(pth_file_path, paths_to_write)
综合案例
读取和写入 .pth
文件的综合案例
import os
def read_pth_file(pth_file):
with open(pth_file, 'r') as file:
lines = file.readlines()
paths = []
for line in lines:
line = line.strip()
if line and not line.startswith('#'):
if line.startswith('import'):
exec(line)
else:
paths.append(line)
return paths
def write_pth_file(pth_file, paths):
with open(pth_file, 'w') as file:
for path in paths:
file.write(path + '\n')
# 示例:读取并修改一个 .pth 文件
pth_file_path = '/path/to/your/file.pth'
# 读取现有的路径
existing_paths = read_pth_file(pth_file_path)
print('Existing paths:', existing_paths)
# 添加新的路径
new_paths = [
'/new/absolute/path',
'new/relative/path'
]
all_paths = existing_paths + new_paths
# 写入新的路径
write_pth_file(pth_file_path, all_paths)
# 验证写入
updated_paths = read_pth_file(pth_file_path)
print('Updated paths:', updated_paths)
方法三:直接读取pth文件(通过逐行解析)
案例一:直接读取pth文件
# 假设有一个pth_file.pth文件
pth_file_path = 'pth_file.pth'
# 直接读取文件内容
with open(pth_file_path, 'r') as file:
content = file.read()
print(content)
案例二:使用read_pth_file()函数用于解析.pth文件,返回一个路径列表。然后,我们可以将这些路径逐个添加到模块搜索路径中。(这个例子来源于python读取.pth文件 原创)
def read_pth_file(file_path):
paths = []
with open(file_path, 'r') as file:
for line in file:
line = line.strip()
if line and not line.startswith('#'):
paths.append(line)
return paths
# 读取.pth文件
file_path = '/path/to/your.pth'
paths = read_pth_file(file_path)
# 将路径添加到模块搜索路径中
for path in paths:
sys.path.append(path)
读取/写入 npy 文件
.npy文件是NumPy
用于存储数组数据的格式,它们可以很方便地读取和写入。
简单情况
- 读取numpy
# 读取.npy文件
loaded_arr = np.load('arr.npy')
print(loaded_arr)
- 写入numpy
import numpy as np
# 创建一个数组
arr = np.array([[1, 2, 3], [4, 5, 6]])
# 写入到.npy文件
np.save('arr.npy', arr)
复杂情况,使用npz文件读取写入多个数组
例子1:
import numpy as np
# 创建多个数组
array1 = np.array([1, 2, 3, 4, 5])
array2 = np.array([6, 7, 8, 9, 10])
# 保存多个数组到一个文件
np.savez('arrays.npz', array1=array1, array2=array2)
# 从.npz文件加载数组
loaded = np.load('arrays.npz')
loaded_array1 = loaded['array1']
loaded_array2 = loaded['array2']
print(loaded_array1)
print(loaded_array2)
例子2:
# 创建一个数组
arr = np.array([[1, 2, 3], [4, 5, 6]])
# 写入多个数组到.npz文件
np.savez('arrays.npz', a=arr, b=arr*2)
# 读取.npz文件
with np.load('arrays.npz') as data:
a = data['a']
b = data['b']
print(a)
print(b)
以上是一些常见的方法来读取和写入 txt、Excel 和 JSON 文件。每种方法都有其优缺点,选择哪种方法取决于具体的需求和使用场景。

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)