Python 文件操作实例:轻松读写 txt 与 CSV
·
在 Python 中,文件操作是编程中非常常见的任务之一。无论是处理文本文件(如 .txt)还是表格文件(如 .csv),Python 都提供了简单而强大的方法来读取和写入文件。今天,就让我们一起学习如何在 Python 中轻松读写 .txt 和 .csv 文件,并分享一些实用的技巧和最佳实践。
一、读写 .txt 文件
(一)读取 .txt 文件
示例代码
# 打开并读取一个文本文件
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()) # 使用 strip() 去除行尾的换行符
(二)写入 .txt 文件
示例代码
# 写入一个文本文件
with open('output.txt', 'w', encoding='utf-8') as file:
file.write("Hello, World!\n")
file.write("This is a test.\n")
追加内容
# 追加内容到文本文件
with open('output.txt', 'a', encoding='utf-8') as file:
file.write("This is another line.\n")
二、读写 .csv 文件
(一)读取 .csv 文件
使用 csv 模块
import csv
# 打开并读取一个 CSV 文件
with open('example.csv', 'r', encoding='utf-8') as file:
reader = csv.reader(file)
for row in reader:
print(row) # 每行是一个列表
使用 DictReader 读取
import csv
# 使用 DictReader 读取 CSV 文件
with open('example.csv', 'r', encoding='utf-8') as file:
reader = csv.DictReader(file)
for row in reader:
print(row) # 每行是一个字典
(二)写入 .csv 文件
使用 csv 模块
import csv
# 写入一个 CSV 文件
data = [
['Name', 'Age', 'City'],
['Alice', 25, 'New York'],
['Bob', 30, 'Los Angeles'],
['Charlie', 35, 'Chicago']
]
with open('output.csv', 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerows(data)
使用 DictWriter 写入
import csv
# 使用 DictWriter 写入 CSV 文件
data = [
{'Name': 'Alice', 'Age': 25, 'City': 'New York'},
{'Name': 'Bob', 'Age': 30, 'City': 'Los Angeles'},
{'Name': 'Charlie', 'Age': 35, 'City': 'Chicago'}
]
with open('output.csv', 'w', newline='', encoding='utf-8') as file:
fieldnames = ['Name', 'Age', 'City']
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data)
三、文件操作的最佳实践
(一)使用 with 语句
使用 with 语句可以自动管理文件的打开和关闭,避免文件泄漏。
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
(二)指定文件编码
在读写文件时,指定文件的编码(如 utf-8)可以避免编码问题。
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
(三)逐行读取大文件
对于大文件,逐行读取可以节省内存。
with open('example.txt', 'r', encoding='utf-8') as file:
for line in file:
print(line.strip())
(四)使用 csv 模块处理 CSV 文件
csv 模块提供了方便的接口来读写 CSV 文件,支持多种格式化选项。
import csv
with open('example.csv', 'r', encoding='utf-8') as file:
reader = csv.reader(file)
for row in reader:
print(row)
四、总结
通过本文的介绍,你已经学会了如何在 Python 中读写 .txt 和 .csv 文件,并了解了一些实用的技巧和最佳实践。以下是关键点总结:
- 读取
.txt文件:使用open()函数,逐行读取可以节省内存。 - 写入
.txt文件:使用open()函数,write()方法写入内容。 - 读取
.csv文件:使用csv模块,reader和DictReader提供方便的接口。 - 写入
.csv文件:使用csv模块,writer和DictWriter提供方便的接口。 - 最佳实践:使用
with语句管理文件,指定文件编码,逐行读取大文件,使用csv模块处理 CSV 文件。
更多推荐
所有评论(0)