深入dirs \ sub-dirs寻找特定的文件名

时间:2019-05-20 22:28:36

标签: python matching

深入子目录以查找要修改的特定文件。

使用glob.glob()在所有子目录中搜索文件。

path = 'C:\Test\*\*[1234,349,4568]*.*'
#print(path)

files = glob.glob(path)
print(files)
for name in files:
        with open(name,'r') as inputfile:
            newText = inputfile.read().replace('5484522-102','P/N 545616-102')
            print(newText)
        with open(name, "w") as outputfile:
            outputfile.write(newText)
print('Done !')

修改路径中调用的文件,还有更多我不想修改的文件。如何只修改路径中标注的文件?

1 个答案:

答案 0 :(得分:0)

#!/usr/bin/env python3

#This code finds the specific files listed in a dir and copies them to another dir.  
There the files are read and the p/n replace with another p/n

import os
import shutil
import glob
import pandas as pd


#fill in the file name into this set
df = pd.read_csv('c:\Test\ReadFiles.csv')

path = 'C:\Test\Test\*.*'
dest_dir = 'C:\Test\Test' # New dir for the files found
src_dir = 'C:\Test' # Search dir

遍历目录和文件以在set()中查找文件。

 for (dirpath, dirnames, filenames) in os.walk(src_dir):
    for fname in filenames:
        if fname[:6] in df: 
            print(fname)
            shutil.copy(os.path.join(dirpath, fname), dest_dir) 

浏览找到的文件并更改部件号

files = glob.glob(path)
print(files)
for name in files:
        with open(name,'r') as inputfile:
            newText = inputfile.read().replace('222222-101','111111-101')
        with open(name, "w") as outputfile:
             outputfile.write(newText)
             print(outputfile)
 print('Done !')