Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing of all files in directory?

Tags:

python

pathlib

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:

enter image description here

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.

like image 569
Akrios Avatar asked Oct 07 '16 04:10

Akrios


People also ask

How do you get a list of all files in a directory?

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:\>”.

What is the command to list all files?

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.

How do I show all files in a directory in command prompt?

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.

How do you get a list of all files in a directory in Python?

os. listdir() method gets the list of all files and directories in a specified directory. By default, it is the current directory.


1 Answers

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()] 

More from the pathlib module:

  • pathlib, part of the standard library.
  • Python 3's pathlib Module: Taming the File System
like image 173
prasastoadi Avatar answered Oct 09 '22 13:10

prasastoadi