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

代码整体结构:

一、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()

运行结果:

  • 10
    点赞
  • 66
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沧海黎明

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值