Home > Enterprise >  How to get the pure file path from tkinter's filedialog.askopenfile()?
How to get the pure file path from tkinter's filedialog.askopenfile()?

Time:01-18

I'm using sourceDir = filedialog.askopenfile() to get a file's path, so when I choose the file and print its path, I want to get D:/GitHub/repo/test.jpg, but instead I'm getting <_io.TextIOWrapper name='D:/GitHub/repo/test.jpg' mode='r' encoding='cp1250'>. How can I print only the "name"?

Here's a simplified version of my whole code

from tkinter import Tk
from tkinter import filedialog

sourceDir = ""

sourceDir = filedialog.askopenfile()
print(f"source file: {sourceDir}")
input("")

CodePudding user response:

In the code sourceDir = filedialog.askopenfile() that was posted in the original question, the filename can be accessed via sourceDir.name.

Alternatively, the tkinter.filedialog module has an askopenfilename function. This function will only return the filename string.

sourceDir = filedialog.askopenfilename()
print(f"source file: {sourceDir}")

CodePudding user response:

you can use sourceDir.name

which will give you the "D:/GitHub/repo/test.jpg"

sourceDir = filedialog.askopenfile() print(f"source file: {sourceDir.name}")

CodePudding user response:

@bruhfunnydev, I think what you want to do is:

from tkinter import Tk
import tkinter as tk

root = tk.Tk()

file = filedialog.askopenfile(parent=root, mode='rb', title='Choose your file:')

root.withdraw()

print(file)
  •  Tags:  
  • Related