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
#7
(Jul-13-2020, 02:58 PM)12237ee1 Wrote: 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

Usually you save your data in your homedirectory.

If your username is 12237ee1, then path to your home directory is: /home/12237ee1/. Put your file into your home directory. If you open your terminal window, you're already loged in with your user. Use pwd to show the Path where you are.

Applying the set on a regular str does not what you want:
In [1]: set("/home/file.txt")                                                                                                
Out[1]: {'.', '/', 'e', 'f', 'h', 'i', 'l', 'm', 'o', 't', 'x'}
You need the lines in a sequence and then you can consume them with a set.

with open("/home/12237ee1/file.txt") as fd:
    unique_lines = set(fd)
fd is an iterator, which yields lines (with line ending).
The set() takes those elements. Identical lines are removed and the order is not preserved.

But these are the basics. You need to know what a file object is, what iterables are and what the different data types does with it.
Otherwise, you'll not understand how Python works. I call it brute-force programming, what you do.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
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,251 Sep-09-2021, 01:25 PM
Last Post: Yoriz
  .pth file does not show up in sys.path when configuring path. arjunsingh2908 2 5,827 Jul-03-2018, 11:16 AM
Last Post: arjunsingh2908
  scandir() recursively and return path + filename malonn 6 17,423 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