I am trying to create a script that will search through a user input file path and open all the .cix file type and replace line 27.
What I have so far works on individual folders opening the files within one at a time and modifying the desired line. But if I try to use it on a folder with subfolders it's not working. It is opening and saving the file but it's not changing the line and I can't figure out where I am going wrong.
from tkinter import *
import os
root = Tk()
root.geometry('400x75')
root.title('Labels Off')
dirLabel = Label(root, text='Directory Path:').pack()
e = Entry(root, width='50')
e.pack()
os.listdir(path='.')
def replace(filename):
f = open(filename, 'r')
lines = f.readlines()
print(filename)
f.close()
if 'ENABLELABEL=1' in lines[27]:
lines[27] = ' ENABLELABEL=0\n'
elif 'ENABLELABEL=0' in lines[27]:
lines[27] = ' ENABLELABEL=1\n'
else:
print('err')
f = open(filename, 'w')
f.write(''.join(lines))
f.close()
def getListOfFiles(dirName):
# create a list of file and sub directories
# names in the given directory
listOfFile = os.listdir(dirName)
allFiles = list()
# Iterate over all the entries
for entry in listOfFile:
# Create full path
fullPath = os.path.join(dirName, entry)
# If entry is a directory then get the list of files in this directory
if os.path.isdir(fullPath):
allFiles = allFiles + getListOfFiles(fullPath)
else:
allFiles.append(fullPath)
counter = 0
for file in allFiles:
if file.endswith('.cix'):
replace(file)
else:
allFiles.pop(counter)
counter += 1
return allFiles
def run():
dirName = e.get()
getListOfFiles(dirName)
e.delete(0, END)
submit = Button(root, text='Run', command=run).pack()
mainloop()
OK, i don't know exactly what was wrong with my previous method of creating a file list but something wasn't working right. After trying for a while i replaced my previous method with this and it now works perfectly,
def getListOfFiles(dirName):
allFiles = []
for r, d, f, in os.walk(dirName):
for file in f:
if '.cix' in file:
allFiles.append(os.path.join(r, file))
for file in allFiles:
replace(file)
return allFiles