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
Related
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?
This question already has answers here:
How do I do a case-insensitive string comparison?
(15 answers)
Closed last year.
import time
while True:
npc=input("Josuke\n\nJotaro Kujo (Part 4)\n\nChoose NPC to talk to.")
if npc=="Josuke" or npc=="josuke":
confirm=input("[Press E to interact.]")
elif npc=="jp4" or npc=="JP4" or npc=="Jp4
Within this code you can see that there are 2 NPCs to interact to. Because there are many ways of addressing the name Jotaro Kujo (Part 4), the if statement has many "or"s, but I want to be able to condense it. Could I use an array to be able to put the possibilities in and then have the if statement identify if the value is within the array? (I haven't completed the code yet, but the problem doesn't require the full code to be completed.)
Yes, you can do it easily using the in operator to check if a particular string is in the list.
as an example:
lst = ["bemwa", "mike", "charles"]
if "bemwa" in lst:
print("found")
And if all the possibilities you want to cover are related to case-insensitivity you can simply convert the input to lower-case or upper-case and compare it with only one possibility.
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!
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:]))
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.