How to list files in a directory in python?

Question:

I am unable to list files in a directory with this code

import os
from os import listdir
def fn():       # 1.Get file names from directory
    file_list=os.listdir(r"C:UsersJerryDownloadsprankprank")
    print (file_list)

 #2.To rename files
     fn()

on running the code it gives no output !

Asked By: Jaskunwar singh

||

Answers:

You should use something like this

for file_ in os.listdir(exec_dir):
  if os.path.isdir(exec_dir+file):
        print file_

I hope this is useful.

Answered By: i.q.

The function call fn() was inside the function definition def fn(). You must call it outside by unindenting the last line of your code:

import os
def fn():       # 1.Get file names from directory
    file_list=os.listdir(r"C:Users")
    print (file_list)

 #2.To rename files
fn()
Answered By: nikpod

if you want to list all files including sub dirs.
you can use this recursive solution

import os
def fn(dir=r"C:UsersaryanDownloadsopendatakit"): 
    file_list = os.listdir(dir)
    res = []
    # print(file_list)
    for file in file_list:
        if os.path.isfile(os.path.join(dir, file)):
                res.append(file)
        else:
            result = fn(os.path.join(dir, file))
            if result:
                res.extend(fn(os.path.join(dir, file)))
    return res


res = fn()
print(res)
print(len(res))
Answered By: JaY KuMaR
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.