Can anybody help me create a function which will create a list of all files under a certain directory by using pathlib
library?
Here, I have a:
I have
c:\desktop\test\A\A.txt
c:\desktop\test\B\B_1\B.txt
c:\desktop\test\123.txt
I expected to have a single list which would have the paths above, but my code returns a nested list.
Here is my code:
from pathlib import Path def searching_all_files(directory: Path): file_list = [] # A list for storing files existing in directories for x in directory.iterdir(): if x.is_file(): file_list.append(x) else: file_list.append(searching_all_files(directory/x)) return file_list p = Path('C:\\Users\\akrio\\Desktop\\Test') print(searching_all_files(p))
Hope anybody could correct me.
Start -> Run -> Type in “cmd” This will open the command window. Next I will have to move into the correct directory. On my computer, the default directory is on the C: drive, but the folder I want to list the files for is on the D: drive, the first thing I will see is the prompt “C:\>”.
The ls command is used to list files or directories in Linux and other Unix-based operating systems. Just like you navigate in your File explorer or Finder with a GUI, the ls command allows you to list all files or directories in the current directory by default, and further interact with them via the command line.
You can use the DIR command by itself (just type “dir” at the Command Prompt) to list the files and folders in the current directory.
os. listdir() method gets the list of all files and directories in a specified directory. By default, it is the current directory.
Use Path.glob()
to list all files and directories. And then filter it in a List Comprehensions.
p = Path(r'C:\Users\akrio\Desktop\Test').glob('**/*') files = [x for x in p if x.is_file()]
pathlib
module:If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With