Python Forum
Get the filename from a path
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Get the filename from a path
#6
(Jul-12-2020, 10:11 AM)DeaD_EyE Wrote: Iterate over the open file, then you get line by line.
Instead of regex you could use str.rsplit() or str.rpartition().

pdf_files = set()
# https://docs.python.org/3/library/stdtypes.html#set

with open(file) as fd:
    for line in file:
        url, last = line.strip().rsplit("/", 1)
        # https://docs.python.org/3/library/stdtypes.html#str.rsplit
        print(last)
        # then check if last.endswith(".pdf")
        # if true, add it to the set


# Now sort pdf_files with sorted
# https://docs.python.org/3/library/functions.html#sorted
sorted_pdfs = sorted(pdf_files)
PS: If in one line is more than one address, you could split them with the split() method.

I am using linux so where should I put the path of the file in the script
I tried it like this
a= "/home/file.txt"
pdf_files = set(a)
but it didn't work .. also I need the result without brackets only the name of one file in each line
thank you
Reply


Messages In This Thread
Get the filename from a path - by 12237ee1 - Jul-12-2020, 07:03 AM
RE: Get the filename from a path - by ndc85430 - Jul-12-2020, 07:08 AM
RE: Get the filename from a path - by DeaD_EyE - Jul-12-2020, 10:11 AM
RE: Get the filename from a path - by 12237ee1 - Jul-13-2020, 02:58 PM
RE: Get the filename from a path - by DeaD_EyE - Jul-13-2020, 04:10 PM
RE: Get the filename from a path - by 12237ee1 - Jul-13-2020, 06:01 PM
RE: Get the filename from a path - by Yoriz - Jul-12-2020, 10:33 AM
RE: Get the filename from a path - by DeaD_EyE - Jul-12-2020, 11:41 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  WebDriverException: Message: 'PATH TO CHROME DRIVER' executable needs to be in PATH Led_Zeppelin 1 2,246 Sep-09-2021, 01:25 PM
Last Post: Yoriz
  .pth file does not show up in sys.path when configuring path. arjunsingh2908 2 5,819 Jul-03-2018, 11:16 AM
Last Post: arjunsingh2908
  scandir() recursively and return path + filename malonn 6 17,403 May-09-2018, 03:45 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020