7:文件操作和异常
1:读取完一个大文件
with open('1.txt','r') as f:
content=f.readline()
while len(content)>0:
print(content)
content=f.readline()
2:读取完一个大文件中包含指定字符python的行
with open('1.txt','r') as f:
count=0
content=f.readline()
while len(content)>0:
if 'python' in content:
count += 1
print(content)
content=f.readline()
print(f'python字符出现的次数{count}')
3:制作文件的备分
1.txt内容备份成1备份.txt
old_file=input('请输入当前路径下的文件名用来备份:')
#最后.的下标
num=old_file.rfind('.')
#[0:num]不包含. [num:]包含.以后的数据
new_file=old_file[0:num]+'备份'+old_file[num:]
old=open(old_file,'r')
new=open(new_file,'w')
#读的是字符串+换行
content=old.readline()
while len(content)>0:
# 写的是字符串+换行
new.write(content)
content=old.readline()
new.close()
old.close()
4:批量修改重命名指定目录下的所有文件
上个目录下的test目录下存在文件
import os
listdir=os.listdir('../test')
for temp in listdir:
new_file='abc-'+temp
#切换目录
os.chdir('../test')
os.rename(temp,new_file)

浙公网安备 33010602011771号