栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python基础知识—文件批量处理

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python基础知识—文件批量处理

Python基础知识—文件批量处理
  • 找到所有文件
    • os.listdir()
    • os.path.join()
  • 找到文件特定字段
    • re.findall()
    • os.path.join()
  • 替换
    • os.path.join()
    • re.sub()
    • string.startwith()

Q: 找到所有文件中的特定字段,然后替换掉这个特定字段

1)初步思考
  • 步骤:
    • 遍历所有文本文件
    • 找到文件中特定字段
    • 替换掉这个特定字段
2)找到所有文件
import os
print(os.listdir("../test"))

['new_file.txt']
3)找到文件特定字段
for filename in os.listdir("../test"):
    file_path = os.path.join("test", filename)
    with open(file_path, "r") as f:
        print(file_path, ":", f.read())
        
new_file.txt : some text...
add new line
百度 https://baidu.com, 这个 www.baidu.com 可以访问到百度
import re

string = "百度 https://baidu.com, 这个 www.baidu.com 可以访问到百度"
res = re.findall(r"(http://)?(baidu.com)", string)
for r in res:
    print(r[1])
    
baidu.com
baidu.com
4)替换

有俩个方案:

  • 在原文本上替换,并覆盖原文本的内容
  • 复制出一个新的文件,将原文本替换过的文字拷贝到新文件中,原文件不改变
for filename in os.listdir("../test")
	  file_path = os.path.join("test", filename)
    with open(file_path, "r") as f1:
        string = f1.read()
        new_string = re.sub(r"baidu.com", "google.com", string)
        with open(os.path.join("test", "new_"+filename), "w") as f2:
            f2.write(new_string)
for filename in os.listdir("../test"):
		if filename.startswith("new_"):
				continue
    file_path = os.path.join("test", "new_"+filename)
    with open(file_path, "r") as f:
        print(file_path, ":", f.read())
        
some text...
add new line
百度 https://google.com, 这个 www.google.com 可以访问到百度

参考:[莫烦Python](

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/423737.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号