萌新学 Python 之 with 文件操作语句
with 语句用于资源管理,避免资源泄露,对文件操作时,不管文件是否有异常,都会自动清理和关闭
with 语句的格式:
with open('文件路径', mode='模式', encoding='utf-8') as file_obj: # as 取别名
print('对文件进行操作,操作完成后不需要则 close 关闭文件')
pass
举个简单的例子:读取 d 盘下的指定文件,r 是只读,w 是只写
read(),读取文件内容,保存的是字符串
write(),写入内容
with open(r'd:\test.txt', mode='r', encoding='utf-8') as f:
content = f.read() # 读取文件内容,保存到 content 中(保存的是 str 字符串类型)
print(content)
在指定位置插入新内容:
因为原 test.txt 文本有内容,如果在末尾添加新内容,先要计算字符串长度,再在后面添加,
中间插入同理,需要用到索引下标切片,若是修改内容,在修改的字符串位置写入新内容即可
注意,写入操作完成后,自动关闭,需要再读取文件重新打开
# 在指定位置插入内容
with open(r'd:\test.txt', mode='r', encoding='utf-8') as f1:
content = f1.read()
str_len = 4
new_content = content[:str_len] + '\n你好' + content[str_len:]
# 新内容写入原文件
with open(r'd:\test.txt', mode='w', encoding='utf-8') as f2:
f2.write(new_content)
# 上面操作文件自动关闭了,需要重新打开
with open(r'd:\test.txt', mode='r', encoding='utf-8') as f3:
print(f3.read())
在指定行插入新内容:
readlines(),内容返回列表
insert 插入,下标从 0 开始,如果原行数不够,在末尾插入
writelines(),新内容写入行
# 在指定行插入新内容
with open(r'd:\test.txt', mode='r', encoding='utf-8') as f1:
content = f1.readlines() # 内容返回列表
print(content)
content.insert(2, '你好') # 下标从0开始,实则是在第三行插入内容,若是原行数不够,在末尾插入
with open(r'd:\test.txt', mode='w', encoding='utf-8') as f2:
f2.writelines(content) # 将新内容写入行
with open(r'd:\test.txt', mode='r', encoding='utf-8') as f3:
print(f3.read())
案例:创建一个目录 file_txt,生成 10 个 001.txt,...,010.txt 文件,并且每个文件随机写入 10 个 a ~ z 的字母
先判断目录是否存在 os.path.exists(path)
创建目录 os.makedirs(path)
for 循环生成 10 个文件,os.path.join() 路径拼接文件路径
注意 '{:03d}.txt'.format(i) 格式化输出要加冒号,前面是索引位置
文件 w 只写,random.choices() 从给定的序列中随机选择元素
string.ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz' 字母小写
抽取 10 次结果返回,概率一致,写入生成的文本文件
# 创建一个目录 file_txt,生成 10 个 001.txt,...,010.txt 文件,并且每个文件随机写入 10 个 a ~ z 的字母
import os.path
import random
import string
path = './file_txt' # 在当前文件指定目录的路径
if not os.path.exists(path): # 如果该目录不存在
os.makedirs(path) # 创建目录
for i in range(1, 11):
file_name = os.path.join(path, '{:03d}.txt'.format(i))
with open(file_name, mode='w') as f:
random_str = ''.join(random.choices(string.ascii_lowercase, k=10))
f.write(random_str)
可以看到生成目录,目录下生成文本文件
打开看,每个文件随机生成 10 个字母