代码整体结构:
一、Python实现读取文本内容
# -*- coding: utf-8 -*-
"""
@date: 2022/01/11 18:40
@author: Anker
@file_read.py:python读取文本文件中的内容
"""
filepath_current = "./test.txt" # test.txt文件在当前项目工程路径下
filepath_appoint = "C:\\Users\\97571\\Desktop\\test\\test.txt" # test.txt文件在指定路径下
# 方法一:
f_open = open(filepath_current, 'r+', encoding='utf-8') # 打开文本文件
content = f_open.read() # 读取文本文件中的内容
print(content) # 打印文本文件中的内容
f_open.close() # 关闭操作
# 方法二:
with open(filepath_current, 'r+', encoding='utf-8') as file_read: # 打开文本文件,并读取内容
while True:
lines = file_read.readline() # 读取整行数据
if not lines: # 判断是否为空,如果有空,在break
break
print(lines)
运行结果:
二、Python实现文件重命名
# -*- coding: utf-8 -*-
"""
@date: 2022/01/11 18:40
@author: Anker
@file_rename.py:python批量修改文件名
"""
import os
fold_dir = 'E:\\游戏测试' # 需要修改的文件所在的文件夹
filename = os.listdir(fold_dir) # 该文件夹中文件的名称
print(filename) # 在控制台输出原文件名称
for number, temp in enumerate(filename): # 编号,和得到各文件名
new_filename = '/苍老师小电影001'+str(number+1)+'.mp4' # 新文件名(注意跟上文件后缀名)
os.rename(fold_dir+'/'+temp, fold_dir + new_filename) # 文件重命名后替换原文件名
print(new_filename) # 在控制台输出替换后的文件名称
三、Python实现替换文本内容
1、替换后保存至原文件
# -*- coding: utf-8 -*-
"""
@date: 2022/01/11 18:40
@author: Anker
@content_rename.py:python修改文本文件内容,并保存至到原文本文件中
"""
# 将本地的test.txt文本文件内容中所有为“温州”的全部替换为"杭州",并写入到原来的文本文件中
f1 = open("./test.txt", 'r+', encoding='utf-8') # 打开本地的test.txt文本文件
content = f1.read() # 读取text文本文件中的内容
print("原文件内容为:"+'\n' + content)
f1.close() # 关闭操作
customary_content = "杭州"
new_content = "张三丰"
name = content.replace(customary_content, new_content) # 内容替换
if customary_content not in content: # 判断要替换的内容是否在文本文件中
print("没有找到你要替换的内容")
else:
with open("./test.txt", "w", encoding='utf-8') as f2: # 再次打开test.txt文本文件
f2.write(name) # 将替换后的内容写入到test.txt文本文件中
print("替换成功!" + '\n' + "替换后的内容为:" + name)
运行结果:
2、替换后保存至另外一个文件
# -*- coding: utf-8 -*-
"""
@date: 2022/01/11 18:40
@author: Anker
@file_in_out.py:python修改文本文件内容,并保存至另外一个文本文件中
"""
# 将本地的test1.txt文本文件内容中所有为“杭州”的全部替换为"上海",并输出到text2.txt文本文件中
infile = open("./test1.txt", 'r+', encoding='utf-8') # 打开文本文件
outfile = open("./test2.txt", 'w', encoding='utf-8') # 输出文本文件
# 内容替换,并写入到text2.txt文件中
for line in infile:
outfile.write(line.replace('杭州', '上海'))
# 文件关闭
infile.close()
outfile.close()
运行结果: