在python中使用Windows资源管理器浏览器存储文件路径 [英] storing file path using windows explorer browser in python

查看:890
本文介绍了在python中使用Windows资源管理器浏览器存储文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用python编写了一些加密代码,该代码从用户那里获取原始输入消息,然后使用AES对其进行加密和解密.现在我想增强工作效率,我希望我可以从代码中打开Windows资源管理器并浏览到计算机上的任何文件,选择它,然后按确定"按钮,文件路径存储在变量中,这样我就可以使用进行处理.

I have written some encryption code in python that takes raw input message from user and then encrypts and decrypts it using AES. Now i want to enhance the working and i want that i can open the windows explorer from my code and browse to any file on my computer, select it and when i press OK button the path to file is stored in a variable so i can use it for processing.

我搜索了很多论坛,我设法打开了Windows资源管理器,但是没有传统的确定"和取消"按钮.如果用户按确定"按钮,则文件的路径应存储在我的代码变量中.

I have search many forums, i have managed to open windows explorer but there is no traditional OK and Cancel button. If user presses OK button the path to the file should be stored in my code variable.

在这方面的任何帮助将不胜感激.

Any help in this regard will be highly appreciated.

此外,为了让您知道我使用了以下代码:

moreover, just to let you know i have used the following code:

导入操作系统
os.system("start.")

import os
os.system("start .")

,但资源管理器窗口中没有任何取消"或确定"按钮.请帮助

but the explorer window doesnt have any cancel or OK button. Please help

推荐答案

这是因为在Windows中打开文件时看到的实际上不是资源管理器窗口,因此称为通用对话框.我假设您正在引用此对话框:

That is because what you see when you open files in Windows is not actually an Explorer window, it is called a common dialog. I am assuming you are referering to this dialog:

打开公共打开对话框有多种方法,最简单的方法可能就是使用Python标准库中的Tkinter模块,即tkFileDialog模块的askopenfilename.

There are different ways you can go about opening the common open dialog, among the most easiest is probably just using the Tkinter module from the Python standard library, namely the tkFileDialog module's askopenfilename.

示例代码:

import Tkinter
import tkFileDialog

root = Tkinter.Tk()
root.withdraw()

filename = tkFileDialog.askopenfilename(parent=root,title='Open file to encrypt')

关于花括号:您正在使用askopenfilenames告诉Tk您可能想要多个文件名.这就是为什么您会得到一个用大括号括起来的文件名列表的原因.我实际上怀疑是对Python的Tk绑定的疏忽,以便不拆分文件名并返回列表,但这可以通过使用类似于以下代码的代码轻松纠正:

As for the curly braces: You are using askopenfilenames to tell Tk that you possibly want more than one filename. That's why you get a list of filenames enclosed in curly braces. I actually suspect an oversight in Python's Tk binding so that the filenames are not split up and a list is returned, but this is easily remedied using code similar to this:

import re
# ...
# ...
filenames = tkFileDialog.askopenfilenames(parent=root)
files_to_process = re.split("\}\W\{", filenames[1:-1])

如果用户选择多个文件,这将为您提供所选文件名的列表.仅传递单个文件名时它将中断,因此请确保检查这种情况.

This will give you a list of the selected filenames in case the user selects more than one file. It will break when only passed a single filename, so be sure to check for that case.

这篇关于在python中使用Windows资源管理器浏览器存储文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆