文件操作的基本概念

在Python中,文件操作是一个非常基础但重要的功能。Python提供了多种方式来处理文件,包括打开、读取、写入、关闭等操作。

文件的打开与关闭

基本打开方式

1
2
3
4
5
# 打开文件
f = open('file.txt', 'r')

# 关闭文件
f.close()

使用with语句

为了避免忘记关闭文件,我们可以使用with语句,它会自动处理文件的关闭。

1
2
3
4
with open('file.txt', 'r') as f:
# 处理文件
pass
# 文件会自动关闭

文件的读取

读取整个文件

1
2
3
with open('file.txt', 'r') as f:
content = f.read()
print(content)

逐行读取

1
2
3
with open('file.txt', 'r') as f:
for line in f:
print(line.strip())

读取指定大小

1
2
3
4
5
6
with open('file.txt', 'r') as f:
while True:
chunk = f.read(1024) # 每次读取1024字节
if not chunk:
break
print(chunk)

文件的写入

基本写入

1
2
3
with open('file.txt', 'w') as f:
f.write('Hello, world!\n')
f.write('Python is great!\n')

追加写入

1
2
with open('file.txt', 'a') as f:
f.write('Additional content\n')

写入多行

1
2
3
lines = ['Line 1\n', 'Line 2\n', 'Line 3\n']
with open('file.txt', 'w') as f:
f.writelines(lines)

文件的模式

模式 描述
r 只读模式(默认)
w 写入模式,会覆盖原有内容
a 追加模式,在文件末尾添加内容
b 二进制模式
+ 读写模式

二进制文件操作

读取二进制文件

1
2
3
with open('image.jpg', 'rb') as f:
data = f.read()
print(f"Read {len(data)} bytes")

写入二进制文件

1
2
with open('copy.jpg', 'wb') as f:
f.write(data)

文件的位置

获取当前位置

1
2
3
4
with open('file.txt', 'r') as f:
print(f"Current position: {f.tell()}")
f.read(10)
print(f"Current position: {f.tell()}")

设置位置

1
2
3
4
5
with open('file.txt', 'r') as f:
f.seek(5) # 移动到文件的第5个字节
print(f"Current position: {f.tell()}")
content = f.read()
print(content)

文件的属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import os

# 获取文件大小
file_size = os.path.getsize('file.txt')
print(f"File size: {file_size} bytes")

# 检查文件是否存在
if os.path.exists('file.txt'):
print("File exists")

# 获取文件的修改时间
import time
mod_time = os.path.getmtime('file.txt')
print(f"Last modified: {time.ctime(mod_time)}")

实际应用示例

复制文件

1
2
3
4
5
6
7
8
9
10
11
12
def copy_file(src, dst):
with open(src, 'rb') as fsrc:
with open(dst, 'wb') as fdst:
while True:
chunk = fsrc.read(1024 * 1024) # 每次读取1MB
if not chunk:
break
fdst.write(chunk)
print(f"Copied {src} to {dst}")

# 使用函数
copy_file('source.txt', 'destination.txt')

统计文件中的单词数

1
2
3
4
5
6
7
8
9
def count_words(filename):
with open(filename, 'r', encoding='utf-8') as f:
content = f.read()
words = content.split()
return len(words)

# 使用函数
word_count = count_words('file.txt')
print(f"Number of words: {word_count}")

读取CSV文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def read_csv(filename):
with open(filename, 'r', encoding='utf-8') as f:
lines = f.readlines()
headers = lines[0].strip().split(',')
data = []
for line in lines[1:]:
values = line.strip().split(',')
row = dict(zip(headers, values))
data.append(row)
return data

# 使用函数
csv_data = read_csv('data.csv')
for row in csv_data:
print(row)

总结

Python的文件操作是一个非常基础但重要的功能。通过本文的介绍,你应该已经掌握了文件操作的基本方法和技巧。

无论是读取文本文件、写入数据,还是处理二进制文件,Python都提供了简洁而强大的工具。记住,在处理文件时,要始终使用with语句来确保文件的正确关闭,避免资源泄露。

通过合理使用文件操作,你可以轻松处理各种数据存储和读取的需求,为你的Python程序增添更多的功能和灵活性。