углубление в dirs \ sub-dirs в поисках определенных имен файлов - PullRequest
0 голосов
/ 21 мая 2019

детализация в подкаталоги в поисках конкретных файлов для изменения.

Использование 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 голосов
/ 02 июня 2019
#!/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

просматривая каталог и файлы, ища файлы в наборе ().

 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 !')
...