Python listing all files in directory
<p>Can anybody help me creating a function which will creating a list all files under certain directory by using pathlib library?</p>

<p>Here, I have a</p>

<p><a href="http://i.stack.imgur.com/jJMwB.png" rel="nofollow"><img src="http://i.stack.imgur.com/jJMwB.png" alt="enter image description here"></a></p>

<p>I have  </p>

<ul>
<li><p>c:\desktop\test\A\A.txt</p></li>
<li><p>c:\desktop\test\B\B_1\B.txt</p></li>
<li><p>c:\desktop\test\123.txt</p></li>
</ul>

<p>I expected to have a single list which would have path above, but my code return me nested list.</p>

<p>Here is my code:
from pathlib import Path</p>

<pre><code>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))
</code></pre>

<p>Hope anybody could correct me. Thank you</p>

<p>You can use os.listdir(). It will get you everything that's in a directory - files and directories.</p>

<p>If you want just files, you could either filter this down using os.path:</p>

<pre><code>from os import listdir
from os.path import isfile, join
onlyfiles = [files for files in listdir(mypath) if isfile(join(mypath, files))]
</code></pre>

<p>or you could use os.walk() which will yield two lists for each directory it visits - splitting into files and directories  for you. If you only want the top directory you can just break the first time it yields</p>

<pre><code>from os import walk
files = []
for (dirpath, dirnames, filenames) in walk(mypath):
    files.extend(filenames)
    break
</code></pre>

python pathlib