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](

猜你喜欢

转载自blog.csdn.net/Mrwei_418/article/details/121117234