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!
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.