![](/img/trans.png)
[英]how to make changes to a variable that have been done in a function affect the variable globally python
[英]How to access variable globally that have not been defined yet in python?
我正在使用 python 和 tkinter 创建一个程序,您可以浏览一个 excel 文件,该文件包含要搜索路径的文件名列表,如果它找到文件列表,它将允许用户将所有文件压缩到一个复制 zip 文件并保存我对编程很陌生,所以如果这很简单,我深表歉意。 我的问题是我正在尝试使用在 Load_File function 中找到的文件列表,但是当程序启动时用户尚未设置它。 我需要找到一种方法告诉 python 等到用户浏览到 excel 文件,一旦用户设置了文件,就将其全局设置,以便我可以使用文件列表来搜索操作系统。 下面是我的代码:
def load_file():
file_path = filedialog.askopenfilename(filetypes=[('Excel files', '*.xlsx')])
wb = openpyxl.load_workbook(file_path)
sheet = wb.active
file_names = [cell.value for row in sheet.rows for cell in row]
for file_name in file_names:
listbox.insert('end', file_name)
def search_folder(folder, file_name):
# Create an empty list to store the found file paths
found_files = []
for root, dirs, files in os.walk(folder):
for file in files:
if file in file_name:
found_files.append(os.path.join(root, file))
return found_files
folder = r'C:\Path\To\File'
found_files = search_folder(folder, file_names)
我已将 file_name 设置为全局,但如上所述它会抛出错误,因为程序尚未收到。 如果我必须等待用户启动程序然后浏览到该文件,有没有办法将 file_names 放入 search_folder function? 我觉得我的函数结构和 tkniter window 是错误的,这限制了我可以使用的变量 scope。 任何帮助将非常感激!
我想我明白你在做什么;
创建从所选(通过 askopenfilename)excel 工作表读取的 [文件] 名称的列表“file_names”。 然后搜索此列表中每个文件的路径“文件夹”。 如果存在,将“文件夹”路径添加到名称前,保存到列表“found_files”中。 列表框(至少在此处仅用于显示在 excel 文件中找到的文件名。
因此,load_file function 没有返回列表 file_names,包括它并在调用 search_folder function 时调用 function。
def load_file():
file_path = filedialog.askopenfilename(filetypes=[('Excel files', '*.xlsx')])
wb = openpyxl.load_workbook(file_path)
sheet = wb.active
file_names = [cell.value for row in sheet.rows for cell in row]
for file_name in file_names:
listbox.insert('end', file_name)
return file_names # <--- return your list
def search_folder(folder, file_name):
# Create an empty list to store the found file paths
found_files = []
for root, dirs, files in os.walk(folder):
for file in files:
if file in file_name:
found_files.append(os.path.join(root, file))
return found_files
folder = r'C:\Path\To\File'
# found_files = search_folder(folder, file_names)
found_files = search_folder(folder, load_file()) # <-- call the load_file function, the return will be the list with the filenames.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.