文件处理

定义

定义文件路径和文件名

1
2
3
4
5
6
import os

dir_path = ''
file_name = ''

file_path = os.path.join(dir_path, file_name)

打开/关闭文件

open方式

1
2
3
4
5
6
7
8
9
10
# 打开 open()
f = open(file_path, 'r') # 可以是'r'可读, 'w'可写, 'a'追加, 'r+'等不停的文件默认,默认是'r'
print(f.name) # 文件名
print(f.mode) # 读写模式

# 是否关闭
f.closed

# 关闭 close() 避免资源泄露、锁等问题
f.close()

with方式(文件管理器处理)

with open读写文件不需要手动close。

1
2
3
4
5
6
with open(file_path, 'r') as f:
# content = f.read() # 生成全文
# content = f.readlines() # 生成一个列表
# content = f.readline() # 生成一行内容
print(content)
f.closed # => True

逐行读取

1
2
3
with open(file_path, 'r') as f:
for line in f:
print(line, end='')

可控读取字符(每次读取100个字符)

1
2
3
4
5
6
with open(file_path, 'r') as f:
read_size = 100
content = f.read(read_size)
while len(content) > 0:
print(content, end='*') # 为了显示读取过程,使用'*'来断点
content = f.read(read_size)

增加内容

1
2
with open(file_path, 'a') as f:
f.write(f'这是使用a模式所添加内容')

编写内容

1
2
with open('./text.txt', 'w') as f:
f.write(f'这是w模式所编写内容')
1
2
3
4
5
6
7
8
9
with open('test.txt', 'w') as f:
f.write('Test')
f.seek(0) # 重新定位光标
f.wirte('R')

'''
test.txt
Rest
'''

迭代器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class LineIterator:
def __init__(self, file_path):
self.file = open(file_path, 'r')

def __iter__(self):
return self

def __next__(self):
line = self.file.readline()
if line:
return line
else:
self.file.close()
raise StopIteration
line_iter = LineIterator(file_path)

for line in line_iter:
print(line)

生成器

1
2
3
4
5
6
7
8
def line_generator(file_path):
with open(file_path, 'r') as rf:
for line in rf:
yied line

line_gen = line_generator(file_path)
for line in line_gen:
print(line)

例子

读取test.txt文档,并把它复制到新建的test2.txt文档。

1
2
3
4
5
with open(file_path, 'r') as rf:
with open('test2.txt', 'w') as wf:
for line in rf:
wf.write(line)

1
2
3
4
5
6
7
8
with open(file_path, 'r') as rf:
with open('test2.txt', 'w') as wf:
read_siez = 10
content = rf.read(read_size)
while len(content) > 0:
wf.write(content)
content = rf.read(read_size)

复制IMG

1
2
3
4
5
# xb 二进制读写
with open('dog.png', 'rb') as rf:
with open('dog-copy.png', 'wb') as wf:
for line in rf:
wf.write(line)

斐波拉契数列

1
2
3
4
5
6
7
8
9
def fib_generator():
cur, nxt = 0, 1
while True:
yield cur
cur, nxt = nxt, cur+nxt
fib_gen = fib_generator()

for _ in range(10):
print(next(fib_gen))

内存使用情况

1
2
3
4
5
6
7
8
9
10
import tracemalloc

tracemalloc.start()
'''
代码主体
'''
current, peak = tracemalloc.get_traced_memory()
print(f"Current memory usage: {cureent / 1024**2} MB")
print(f"peak memory usage: {peak / 1024**2} MB")
tracemalloc.stop()
1