我正在尝试创建一个脚本,该脚本将搜索用户输入文件的路径并打开所有.cix文件类型并替换第27行。
到目前为止,我的工作是在单个文件夹中一次打开一个文件并修改所需的行。但是,如果我尝试在带有子文件夹的文件夹中使用它,则无法正常工作。它正在打开并保存文件,但未更改行,并且我无法弄清楚哪里出了问题。
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()
getListOfFiles
返回当前目录和所有子目录的文件列表。也
replace
文件调用.cix
。