[英]How to get filename using os.path.basename without the '> extension
I'm trying to get a string that contains only the filename.我正在尝试获取一个仅包含文件名的字符串。 I know you can use
os.path.basename
to get the just the filename without the pathway.我知道您可以使用
os.path.basename
来获取没有路径的文件名。 However, this still keeps the '> portion of the name.但是,这仍然保留了名称的 '> 部分。 I want to only get the filename, without anything else.
我只想获取文件名,没有其他任何东西。
IE IE
<_io.BufferedReader name='C:/Users/Sams PC/Desktop/file.txt'>
#printout using os.path.basename
file.txt'>
##Desired
file.txt
For some context of what I'm using to get this, this is my script (its using tkinter
):对于我用来获取此内容的某些上下文,这是我的脚本(它使用
tkinter
):
def browse():
result=tk.filedialog.askopenfile(parent=root,mode='rb',title='Choose a file')
return result
print(browse())
print(os.path.basename(str(browse())))
You need to use filedialog.askopenfilename
instead of filedialog.askopenfile
to obtain the filename without side effects (like opening a file).您需要使用
filedialog.askopenfilename
而不是filedialog.askopenfile
来获取没有副作用(如打开文件)的文件名。 This returns the full path;这将返回完整路径; you can extract the filename from the fullpath using
os.path.basename
您可以使用
os.path.basename
从完整路径中提取文件名
import os
import tkinter as tk
from tkinter import filedialog
def browse():
root = tk.Tk()
root.withdraw()
fullpath = filedialog.askopenfilename(parent=root, title='Choose a file')
filename = os.path.basename(fullpath)
root.destroy()
return filename
print(browse())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.