Python操作txt,将一堆txt文件里的abc换成def

Python操作txt文件:操作某个文件夹下所有txt文件,将每个txt文件里的abc换成def

假如不考虑文件夹下的文件夹内的文件修改

import os

path = r"C:\Users\Lenovo\Desktop\新建文件夹"
files = os.listdir(path)  # 得到文件夹下的所有文件名称

for file in files:  # 遍历文件夹
    fileType = os.path.splitext(file)
    filename, Type = fileType # 文件夹的Type是空,所以下面可以判断去除,不必再判断是否为文件夹
    if Type == '.txt':
        position = path + '\\' + file  # 构造绝对路径,"\\",其中一个'\'为转义符,或者这样拼接 position = os.path.join(path, file)
        with open(position, "r") as f:  # 打开文件
            data = f.read()  # 读取文件
        data = data.replace('abc', 'def')
        with open(position, "w") as f:  # 打开文件
            f.write(data)

假如想无限套娃,把文件夹内文件夹内txt一直修改下去

import os


def replaceFile(path=r"C:\Users\Lenovo\Desktop\新建文件夹"):
    files = os.listdir(path)  # 得到文件夹下的所有文件名称
    for file in files:  # 遍历文件夹
        fileType = os.path.splitext(file)
        filename, Type = fileType
        if Type == '.txt':
            # position = path + '\\' + file  # 构造绝对路径,"\\",其中一个'\'为转义符
            position = os.path.join(path, file)
            with open(position, "r") as f:  # 打开文件
                data = f.read()  # 读取文件
            data = data.replace('abc', 'def')
            with open(position, "w") as f:  # 打开文件
                f.write(data)
        # 如果要对原来文件夹下的文件夹内的文件修改,无限套娃
        else:
            position = os.path.join(path, file)
            if os.path.isdir(position):
                replaceFile(position)

望采纳

import glob
import os
l = glob.glob(os.getcwd() + os.path.sep + '*.txt')
for i in l:
with open(i, 'r') as o:
s = o.read(-1)
o.close()
with open(i, 'w') as o:
o.write(s.replace('abc', 'def'))
o.close()