1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Python 实现读取文本内容 文件重命名 替换文本内容

Python 实现读取文本内容 文件重命名 替换文本内容

时间:2022-02-16 15:40:50

相关推荐

Python 实现读取文本内容 文件重命名 替换文本内容

代码整体结构:

一、Python实现读取文本内容

# -*- coding: utf-8 -*-"""@date: /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:# 判断是否为空,如果有空,在breakbreakprint(lines)

运行结果:

二、Python实现文件重命名

# -*- coding: utf-8 -*-"""@date: /01/11 18:40@author: Anker@file_rename.py:python批量修改文件名"""import osfold_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: /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: /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()

运行结果:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。