I'm trying to make a script that iterates through folders in a directory and saves the very first one in the folder to a variable. I'm trying to do this because I have folders in a directory with hundreads of .exr files but I only need the first file in the folder to be saved to the directory. I can get it to print out all the files in each folder but thats a bit too much info than I need. Is there an easy way to do this using something like os.walk? This is what I'm working with so far
import os
def main():
dirName = r"F:\FOLDERNAME"
#Get the List of all files in the directory tree at given path
listOfFiles = getListOfFiles(dirName)
#Print the files
for elem in listOfFiles:
print(elem)
if __name__ =='__main__':
main()
Thanks yall!
CodePudding user response:
If you already:
can get it to print out all the files in each folder
And you only want :
the very first one
Then all you need is something like:
first_file = list_of_files[0]
Looks like you're still learning the very basics of coding. I suggest looking up lessons/tutorials on lists, list indexing, and iterables.
CodePudding user response:
If you use os.walk()
, it returns a list of files in each directory. You can print the first one.
for root, dirs, files in os.walk(dirName):
if files:
print(os.path.join(root, files[0]))