【问题标题】:I want to translate a "Read directory" code from php to python我想将“读取目录”代码从 php 转换为 python
【发布时间】:2019-10-29 08:07:19
【问题描述】:

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

这是我的 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
  }
}

正如我所说,我想把它翻译成 Python。

====编辑==== 我尝试这样的事情:

import os
os.listdir("directoryName")

结果是:

['test.txt']

是数组吗?这种情况下怎么用?

您好!

【问题讨论】:

  • 你有没有做过任何研究,至少做了一个基本的尝试?
  • 是的,但不起作用。然后我和专家一起来;)
  • 您应该在问题中包含您的尝试,以及期望的结果、实际结果以及您已经完成的调试。这个网站的重点是帮助您编写代码(而不是为您从头开始编写整个内容)。但只有你把它展示给我们,我们才能做到这一点:)
  • 好吧,好吧……别生气……我知道这个网站的重点……我要编辑我的问题,
  • 我没有生气,我只是想给你一些建议来改善你的问题,让你在这里有更好的体验。

标签: php python code-translation


【解决方案1】:

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

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

【讨论】:

  • 就是这样!我测试了代码,它可以工作。嗯......现在我要把这段代码转换成一个函数来递归地实现它。谢谢!
猜你喜欢
  • 2018-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-07
  • 2011-05-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多