![]() Users/darren/Desktop/test/test 1 level/article 2.rtf If I run this I get the following output: /Users/darren/Desktop/test/article 1.rtf If you want to print out the full path for the file you can replace print(file) with: print(os.path.join(path, file)) In my case, it prints the following: article 1.rtf We will then check to see if that file's name starts with art and if it does we will print out the file name. In each directory we loop through each file. os.walk will allow us to go through all the subdirectories as well. The code is very similar, but now we use os.walk instead of os.listdir. ![]() for path, currentDirectory, files in os.walk("/Users/darren/Desktop/test"): In this section we will look at how we can do this recursively, meaning, listing all files in the given directory and all of its subdirectories where the file starts with a given string/prefix. In the first section we looked at how we can list all files in a given directory with a given string/prefix. In my case, the following prints out: article 1.rtf Find files recursively On each iteration it will check to see if the filename starts with art, if it does, it will print it out. ![]() The above code will loop through all the files in my test directory. To loop through the provided directory, and not subdirectories we can use the following code: for file in os.listdir("/Users/darren/Desktop/test"): In this tutorial I will show you how to list all files in a directory where those files start with a given string/prefix.
0 Comments
Leave a Reply. |