Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我想翻译一个“a”;“读取目录”;从php到python的代码_Php_Python_Code Translation - Fatal编程技术网

我想翻译一个“a”;“读取目录”;从php到python的代码

我想翻译一个“a”;“读取目录”;从php到python的代码,php,python,code-translation,Php,Python,Code Translation,我想翻译一个从目录中读取文件(或其他目录)的代码,您可以使用它。我有PHP的原始代码,但我想翻译成Python。 我对python的了解非常基础,但我想我能理解你的答案(无论如何,欢迎发表一些评论) 这是我的PHP代码: $dir = opendir("directoryName"); while ($file = readdir($dir)){ if (is_dir($file)){ echo "[".$file . "]<br />"; //You can d

我想翻译一个从目录中读取文件(或其他目录)的代码,您可以使用它。我有PHP的原始代码,但我想翻译成Python。 我对python的了解非常基础,但我想我能理解你的答案(无论如何,欢迎发表一些评论)

这是我的PHP代码:

$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
  }
}
结果是:

['test.txt']
是数组吗?在这种情况下如何使用


你好

在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)

有关更多信息,您可以查看问题。

这里有一种在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)

有关更多信息,您可以查看问题。

您是否做过任何研究,至少做了一次基本尝试?是的,但不起作用。然后我和专家们一起来;)您应该在问题中包括您的尝试,以及期望的结果、实际结果和您已经完成的调试。本网站的全部目的是帮助您编写代码(而不是为您从头开始编写整个内容)。但我们只能这样做,如果你给我们看:)好的,好的。。。别生气。。。我知道这个网站的意义。。。。我要编辑我的问题,我没有生气,我只是想给你一些建议来改进你的问题,让你在这里有更好的体验。你做过任何研究,至少做了一次基本的尝试吗?是的,但不管用。然后我和专家们一起来;)您应该在问题中包括您的尝试,以及期望的结果、实际结果和您已经完成的调试。本网站的全部目的是帮助您编写代码(而不是为您从头开始编写整个内容)。但我们只能这样做,如果你给我们看:)好的,好的。。。别生气。。。我知道这个网站的意义。。。。我要编辑我的问题,我没有生气,我想给你一些建议来改进你的问题,让你在这里有更好的体验。就是这样!我对代码进行了测试,它运行正常。好。。。现在我将把这段代码转换成一个函数,以递归的方式实现它。谢谢就是这样!我对代码进行了测试,它运行正常。好。。。现在我将把这段代码转换成一个函数,以递归的方式实现它。谢谢