3

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:\Users\Jerry\Downloads\prank\prank")
    print (file_list)

 #2.To rename files
     fn()

on running the code it gives no output !

9
  • Is your function even being called? From what you've posted, it looks like the call to fn() is inside the definition of fn() Commented Jun 12, 2017 at 8:13
  • Do you get any errors? Commented Jun 12, 2017 at 8:15
  • @khelwood .. Sir I am new to python ! how do i solve it ? Commented Jun 12, 2017 at 8:17
  • @xunatai No not at all! Commented Jun 12, 2017 at 8:17
  • unindent the last line of your code, fn() Commented Jun 12, 2017 at 8:17

3 Answers 3

13

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Remove the from os import listdir line too
1

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.

1 Comment

edit your answer, highlight the code, press ctrl k .
0

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

import os
def fn(dir=r"C:\Users\aryan\Downloads\opendatakit"): 
    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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.