How to shorten a path (string) to just the file [duplicate] - python

This question already has answers here:
Extract file name from path, no matter what the os/path format
(22 answers)
Closed 3 years ago.
I'm currently making an autosave function for a program based in python, and I have very little knowledge of python. I remember learning how to cut, but this is a bit more of an advanced cut. Right now, I have it printing me the path file in string format (no I cannot use os.path or anything like that) and what I want, is for it to remove the entire path except for NAME.pse(The name will change as well). Here is an example path and ultimately what I'd like it to look like, but I would like for it to work with any path that it prints out so it has compatibility with anyone's computer in any file structure, along with any name of the session file (the .pse):
C:/Users/Install/OneDrive/B&BLab/Coding/TestingCell/PyMol.pse => PyMol.pse

You can use the split() function to split the string at all / characters. This will return a list, then just take the last element of that list:
myString = "C:/Users/Install/OneDrive/B&BLab/Coding/TestingCell/PyMol.pse"
myFile = myString.split('/')[-1]
However, Python does provide a function for this. Check out this answer.

If you want only the filename:
print("".join(stringa.split('/')[-1:]))
And if you want also the containing folder(s):
print("/".join(stringa.split('/')[-2:]))

Related

How to format a string in Python source code for improved readability [duplicate]

This question already has answers here:
How do I split the definition of a long string over multiple lines?
(30 answers)
How can I split up a long f-string in Python?
(2 answers)
Closed 10 months ago.
I'm building a rather long file path, like so:
file_path = f"{ENV_VAR}/my_dir/{foo['a']}/{foo['b']}/{bar.date()}/{foo['c']}.json"
This is a simplified example. The actual path is much longer.
To make this line shorter and more readable in code, I have tried the following:
file_path = f"{ENV_VAR}/my_dir\
/{foo['a']}\
/{foo['b']}\
/{bar.date()}\
/{foo['c']}.json"
This works but also affects the actual string in my program.
More specifically, the linebreaks are added to the string value itself, which is undesirable in this case. I only want to change the formatting of the source code.
Is it possible to format the string without affecting the actual value in my program?

Python: Is there a way to search a directory for all files that contain a given string in the name? [duplicate]

This question already has answers here:
search for a file containing substring in a folder, python?
(3 answers)
Closed 2 years ago.
I'm new to Python and need to search a directory for a specific file given part of the name. For example I have a folder full of many different files:
folder:
file1_dogname.html
file1_catname.html
file2_othername.html
and I need to ask the user which file to open, the options can only be dog, cat, or other. If the user says "dog", I need it to find the file named "file1_dogname.html". Is this possible? Thank you very much for any help!
Take a look at these libraries (you may not even need a library*):
glob
fnmatch
There are a lot of ways to do this!
The best way to learn is to try it out yourself! :)
Here are a few references :
https://pymotw.com/2/glob/
https://www.poftut.com/python-glob-function-to-match-path-directory-file-names-with-examples/
Happy learning!

Regular Expression ".{}." in Python List Comprehensions [duplicate]

This question already has answers here:
What does {0} mean in this Python string?
(6 answers)
Closed 3 years ago.
I'm reviewing code in the popular Deep learning with Python book and came across. The latter part of the code eventually copies 1000 cat images to a directory, and this line stores the file names to fnames.
fnames = ['cat.{}.jpg'.format(i) for i in range(1000)]
Can someone explain how the syntax works, particularly .{}. in this statement? I have used list comprehension in the past, but I'm not following how this line works.
There is no regular expression here. str.format will replace {} with its argument, that's all. There are other ways to use str.format, but that's what it does here. So for each of the thousand numbers generated in range, the comprehension produces one string that is the result of formatting the number via the filename pattern.

Order in which files are read using os.listdir? [duplicate]

This question already has answers here:
Non-alphanumeric list order from os.listdir()
(14 answers)
Python - order of os.listdir [duplicate]
(1 answer)
Closed 5 years ago.
When performing the following code, is there an order in which Python loops through files in the provided directory? Is it alphabetical? How do I go about establishing an order these files are loops through, either by date created/modified or alphabetically).
import os
for file in os.listdir(path)
df = pd.read_csv(path+file)
// do stuff
You asked several questions:
Is there an order in which Python loops through the files?
No, Python does not impose any predictable order. The docs say 'The list is in arbitrary order'. If order matters, you must impose it. Practically speaking, the files are returned in the same order used by the underlying operating system, but one mustn't rely on that.
Is it alphabetical?
Probably not. But even if it were you mustn't rely upon that. (See above).
How could I establish an order?
for file in sorted(os.listdir(path)):
As per documentation: "The list is in arbitrary order"
https://docs.python.org/3.6/library/os.html#os.listdir
If you wish to establish an order (alphabetical in this case), you could sort it.
import os
for file in sorted(os.listdir(path)):
df = pd.read_csv(path+file)
// do stuff

What is partial[1:] doing in this code [duplicate]

This question already has answers here:
Understanding slicing
(38 answers)
Closed 9 years ago.
I am new to python and trying to understand the _full_path from this example.
def _full_path(self, partial):
if partial.startswith("/"):
partial = partial[1:]
path = os.path.join(self.root, partial)
return path
What does the function do? Specifically, what does this line do?
partial = partial[1:]
It seems like some kind of list manipulation -- but I can't find syntax like that in this document.
What is the root property of self that is getting called?
Can somebody explain a little bit about what is happening in that code.
Because os.path.join will take later path start with '/' as base, try this:
print os.path.join('/a', '/b/')
it return '/b/', so you have to check and remove begin slash when you join path.
str is a sequence type, check here: http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange
That line drops the starting "/".
The function itself gives back the "full path".

Categories

Resources