继续学习Python
今天就是文件的操作
1.文件读操作
1.1 read()
# 1.打开文件
f = open('a.txt', 'r', encoding='utf-8')
# 2.读写文件 ,文件对象.read(n) n 一次读取多少字节的内容,默认不写,读取全部内容
buf = f.read(3)
print(buf) # 123
print('-'*30)
buf = f.read(3)
print(buf)
# 3.关闭文件
f.close()
1.2 按行读取文件
f = open('a.txt', 'r', encoding='utf-8')
# f.readline() 一次读取一行内容,返回值是读取到的内容(str)
# buf = f.readline()
# f.readlines() 按行读取, 一次读取所有行, 返回值是列表 ,列表中的每一项是一个字符串,即一行的内容
buf = f.readlines()
print(buf)
buf = [i.strip() for i in buf]
print(buf)
f.close()
2.模拟读取大文件
# read() 一次读取全部的内容
# readline() 读到文件末尾会返回空
f = open('a.txt', 'r', encoding='utf-8')
while True:
buf = f.readline()
if buf:
print(buf, end='')
else:
break
3.文件打开模式
文本文件: txt, .py .md 能够使用记事本打开的文件 二进制文件: 具有特殊格式的文件, mp3 mp4 rmvb avi png jpg 等
文本文件可以使用 文本方式打开文件,也可以使用二进制的方式打开文件
二进制文件,只能使用二进制的方式打开文件 二进制打开方式如下: 不管读取,还是书写,都需要使用二进制的数据 rb wb ab 注意点: 不能指定 encoding 参数
f = open('c.txt', 'wb')
f.write('你好'.encode()) # encode() 将str 转换为二进制格式的字符串
f.close()
f1 = open('c.txt', 'rb')
buf = f1.read()
print(buf)
print(buf.decode())
f1.close()
4.应用-文件备份
# 1.用只读的方式,打开文件
f = open('a.txt', 'rb')
# 2.读取文件内容
buf = f.read()
# 3.关闭文件
f.close()
# 4.只写的方式,打开新文件
f_w = open('a[备份].txt', 'wb')
# 5. 将第2 步读取的内容写入新文件
f_w.write(buf)
# 6.关闭新文件
f_w.close()
文件备份-优化 (文件和文件夹的操作)
file_name = input('请您输入要备份的文件名')
# 1.用只读的方式,打开文件
f = open(file_name, 'rb')
# 2.读取文件内容
buf = f.read()
# 3.关闭文件
f.close()
# 根据原文件名,找到文件后缀名和文件名
index = file_name.rfind('.')
# 后缀名 file_name[index:]
# 新文件名
new_file_name = file_name[:index] + '[备份]' + file_name[index:]
print(new_file_name)
# 4. 只写的方式,打开新文件
f_w = open(new_file_name, 'wb')
# 5. 将第2 步读取的内容写入新的文件
f_w.write(buf)
# 6.关闭新的文件
f_w.close()
5.批量修改文件名
import os
def create_files():
for i in range(10):
file_name = 'test/file_' + str(i) + '.txt'
print(file_name)
f = open(file_name, 'w')
f.close()
def create_files_1():
os.chdir('test')
for i in range(10, 20):
file_name = 'file_' + str(i) + '.txt'
print(file_name)
f = open(file_name, 'w')
f.close()
os.chdir('../')
def modify_filename():
os.chdir('test')
buf_list = os.listdir()
for file in buf_list:
new_file = 'py43_' + file
os.rename(file, new_file)
os.chdir('../')
def modify_filename_1():
os.chdir('test')
buf_list = os.listdir()
for file in buf_list:
num = len('py43_')
new_file = file[num:]
os.rename(file, new_file)
os.chdir('../')
modify_filename_1()