-2

I have created FileDialog to browse file. After choosing the file, I want to get the name of the file only! But I always get full path.. and this is my Code:

self.pushButton_2.clicked.connect(self.pushButton_2_handler)

def pushButton_2_handler (self):
    self.open_dialog_box()

def open_dialog_box(self):
    filename=QFileDialog.getOpenFileName()
    print(filename[0])
Nitin Nain
  • 5,113
  • 1
  • 37
  • 51
Reemi
  • 1
  • 2

2 Answers2

0

You can use the pathlib module:

>>> from pathlib import Path
>>> path = Path("C:/users/foobar/desktop/file.txt")
>>> path.name
'file.txt'
>>> path.stem
'file'
>>> path.suffix
'.txt'
>>> 
Paul M.
  • 10,481
  • 2
  • 9
  • 15
-1

Well file paths go like blah\blah\blah\filename so all you need to do is loop back until you find a \ and use that.

for index in range(len(filename[0])-1, 0,-1):
    if filename[0][index] == "\\": 
        filename[0] = filename[0][index+1:]
        break

you could also split up the string by \ and use the last one like

filename[0] = filename[0].split("\\")[-1]

or use os

import os
filename[0] = os.path.basename(filename[0])
The Big Kahuna
  • 2,097
  • 1
  • 6
  • 19
  • 1
    why is the most reasonable way listed last? Frankly it should be the only one. There is no need to use loops and costume code when there is a library function doing exactly that... – Tomerikoo Apr 04 '20 at 23:30