1

I want to translate a code that read files (or other directories) from directory and you can work with it. I have the code originaly on PHP, but I want to translate to Python. My knowledge of python is so very basic, but I guess I can understand your answers (In any case, some comments are welcome)

This is my PHP code:

$dir = opendir("directoryName");
while ($file = readdir($dir)){
  if (is_dir($file)){
    echo "[".$file . "]<br />";
    //You can do anything with this result
  }
  else{
    echo $file . "<br />";
    //You can do anything with this result
  }
}

As I said, I want to translate that into Python.

====Edit==== I try something like that:

import os
os.listdir("directoryName")

Result is:

['test.txt']

Is an array? how to use that in that case?

Greetings!

Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
Lsyk4
  • 33
  • 4
  • 1
    Have you done any research at all and at least made a basic attempt? – Patrick Q Jun 14 '19 at 16:54
  • Yup, but doesnt works. Then I come with the experts ;) – Lsyk4 Jun 14 '19 at 17:03
  • You should include your attempt in your question, along with the desired result, actual result, and what debugging you have already done. The whole point of this site is to help you with your code (not write the whole thing from scratch for you). But we can only do that if you show it to us :) – Patrick Q Jun 14 '19 at 17:05
  • 1
    Ok, Ok... dont be mad... I Know the point of this site.... I gonna edit my question, – Lsyk4 Jun 14 '19 at 17:13
  • I'm not mad, I'm trying to give you advice to improve your question so you have a better experience here. – Patrick Q Jun 14 '19 at 17:14
  • I improved my question, adding the attempt. Thanks. – Lsyk4 Jun 14 '19 at 17:18

1 Answers1

0

Here is one possible approach to do that in Python:

import os

# Use listdir to get a list of all files / directories within a directory 
# and iterate over that list, using isfile to check if the current element
# that is being iterated is a file or directory.
for dirFile in os.listdir('directoryName'):
    if os.path.isfile(dirFile):
        print('[' + dirFile + ']')
    else:
        print(dirFile)

For more information, you can view this question.

Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
  • 1
    This is it! I test the code and it works. Well... now I gonna convert this code into a function to make it recursively. Thanks! – Lsyk4 Jun 14 '19 at 17:23