使用 Python 文件对话框 askopenfilename() 方法打开文件时如何获取文件类型? [英] How do you get the file type when a file is opened using the Python filedialog askopenfilename() method?

查看:256
本文介绍了使用 Python 文件对话框 askopenfilename() 方法打开文件时如何获取文件类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 python tkinter 编写了这个程序,它使用 tkinter 文件对话框 askopenfilename() 方法打开一个文件.它将获取该文件的内容并将其插入到 TextBox 中.

I have this program written in python tkinter which opens a file using the tkinter filedialog askopenfilename() method. It will get the contents of that file and will insert that into a TextBox.

我希望能够获取该文件的文件类型(即,如果文件是 Python 文件,那么我希望控制台打印.py",如果是 HTML 则我希望它打印.html"; 等等).

I want to be able to get the file type of that file (i.e if the file is a Python file then I want the console to print ".py" if its HTML then I want it to print ".html" and so forth).

所以这就是我尝试过的:

So this is what I tried:

FilePath = filedialog.askopenfilename(initialdir="C:/gui/", title="Open a File", filetypes=(("All Files", "*.*"), ("Text Files", "*.txt"), ("HTML Files", "*.html"), ("CSS Files", "*.css"),("JavaScript Files", "*.js"), ("Python Files", "*.py")))

print(FilePath)

然而,这给了我:/home/Test/RandomFolder/Test.py

However, this gives me: /home/Test/RandomFolder/Test.py

是否可以只获取.py"?最后?

Is it possible to get just the ".py" at the end?

推荐答案

open_File = easygui.fileopenbox(msg="Choose a file", default=r'C:\Users\user\*.txt')

extension = open_File.split('.', 1)

print(extension)

所以我在这里所做的是获取用户路径,因为通常在路径中你不会有 . 任何地方,除非它在文件的末尾,我已经拆分字符串变成2,如果你想要.之前的所有内容,只需使用extension = open_File.split('.', 0),然后使用上面的代码.

So what I've done here is get the users path, and because typically in a path you won't have a . anywhere unless its at the end of a file, I've split the string into 2, if you want the everything before the . just use extension = open_File.split('.', 0), and everything after use the above code.

另外,虽然我在这种情况下使用的是 Easygui,但它适用于任何文件对话框方法,原则是关于您如何从字符串中获取您想要的内容.

Also, although I am using Easygui in this case, it applies to any file dialog method, the principle is in regards to how you're getting what you want out of the string.

这篇关于使用 Python 文件对话框 askopenfilename() 方法打开文件时如何获取文件类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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