Luke Neo
2018-09-09 10:09
采纳率: 20%
浏览 2.5k

如何用 Python 遍历当前目录所有子目录的指定文件进行替换操作?

我想用 Python 遍历当前文件夹下的所有子目录, 并把里面所有的 Test.f03 文件里面的 Source 替换成 Target

# encoding: utf-8
import re
import os
import sys

filepath = []

def AlterContent(filepath):
    Target_File = 'Test.f03'
    FileOpen = open (Target_File,'r')
    w_str = ""
    for line in FileOpen:
        if re.search ('Source', line):
            line = re.sub ('Source', 'Target', line)
            w_str += line
        else:
            w_str += line
    print (w_str)
    WriteOpen = open (Target_File,'w')
    WriteOpen.write (w_str)
    FileOpen.close ()
    WriteOpen.close ()
AlterContent(filepath)

遍历目录的部分怎么写呢.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • 大肥羊2018 2018-09-09 11:56
    已采纳

    “当前目录的所有子目录的指定文件” 是指“当前目录的所有子目录 里面 的指定文件” 吗?
    若果是的话:

    import os
    root = r'd:\\'#当前目录
    list = os.listdir(root)
    fileName = 'Test.f03'
    
    for str in list:
        print(str)
        path = os.path.join(root, str)
    
        if not os.path.isdir(path):
            continue
    
        subpath = os.path.join(path, fileName)
    
        if not os.path.exists(subpath):
            continue
    
        AlterContent(subpath)
    
    点赞 打赏 评论
  • blownewbee 2018-09-09 11:14
     rootdir = ''
    list = os.listdir(rootdir)
    for i in range(0,len(list)):
        path = os.path.join(rootdir,list[i])
        if os.path.isfile(path):
                if path == 'Test.f03':
                        AlterContent(path)
    

    另外,你现有代码的
    Target_File = 'Test.f03'
    需要修改为Target_File = filepath

    点赞 打赏 评论
  • Panstar_ 2018-09-12 01:08

    注释很详细了,主要说一点是,打开文件参数应该传路径+文件名

    #conding=utf8

    import os
    import re

    root = 'F:\wxx\testpycode'#这里填充想要遍历的文件目录
    filename = 'Test.f03'#对比的文件名
    lists = os.walk(root)

    def AlterContent(filepath):#打开的应该是整个文件路径,而不是'Test.f03'
    with open(filepath, 'r', encoding='utf-8') as fr:#读取内容
    content = fr.read()
    #print(content)
    content = re.sub ('Source', 'Target', content)#替换内容
    #print(content)
    with open(filepath, 'w', encoding='utf-8') as fw:#写入新内容
    fw.write(content)

    for path,dirs,files in lists:
    for f in files: #遍历所有文件名
    if f == filename:#应该比较的是文件名
    aimfilepath=os.path.join(path, f)#文件名和目录组成目标文件路径
    print(aimfilepath)
    AlterContent(aimfilepath)

    点赞 打赏 评论
  • lyhsdy 2018-09-12 06:04
     import sys
    import os
    
    
    def replace_filename(file_path, var1, var2):
        for root, dirs, files in os.walk(file_path):
            for file_name in files:
                if var1 in file_name:
                    os.rename(os.path.join(root, file_name), os.path.join(root, file_name.replace(var1, var2)))
                    print('new file name is {0}'.format(file_name.replace(var1, var2)))
    
    
    replace_filename(sys.argv[1], sys.argv[2], sys.argv[3])
    
    点赞 打赏 评论
  • lyhsdy 2018-09-12 06:07
    
     #!coding=utf-8
    import sys
    import os
    
    
    def replace_filename(file_path, var1, var2):
        for root, dirs, files in os.walk(file_path):
            for file_name in files:
                if var1 in file_name:
                    os.rename(os.path.join(root, file_name), os.path.join(root, file_name.replace(var1, var2)))
                    print('new file name is {0}'.format(file_name.replace(var1, var2)))
    
    
    replace_filename(r'E:\你的路径\Test.f03', 'Source', 'Target')###修改下第一个参数即可
    
    
    
    点赞 打赏 评论

相关推荐 更多相似问题