0

I want to convert this GNU command into a python function:

find folder/ 2>/dev/null > file.txt

The find will list all files and folders from the directory recursively and write them to a file.

What I have now in Python is:

import os
project="/folder/path"
i=0
for (project, dirs, files) in os.walk(project):
   print project
   print files
   i += 1

But now I am trying to make the output exactly as find does.

2
  • 2
    Have you read about os.walk yet? After reading that, please update your question to be specific. This is not "write code for me.com" Commented May 19, 2010 at 10:04
  • Thank you, I am sorry for not being clear. Commented May 19, 2010 at 12:09

1 Answer 1

4
import os
path = "folder"
for dirpath, dirnames, filenames in os.walk(path):
    print(dirpath)
    for filename in filenames:
        print(os.path.join(dirpath, filename))

Instead of print you can write to file.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this is the correct solution. I was using print project if len(files) > 0: print files i += 1 but it wasnt joining them. Thank you.
One more thing please, some files are not r-x by everyone or other errors while reading, how can I prevent in Python their inclusion ? (2>/dev/null from find)

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.