drilling down into sub-dirs looking for specific files to modify.

Using glob.glob() to search all sub-dirs for files.

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

modifies the files called out in the path and many more I don't want to be modified. How do i modify only the files called out in the path?

1 Answers

0
Community On Best Solutions
#!/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

walking through the dir and files looking for the files in the 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) 

iterate through files found and change the part number

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