【问题标题】:check if it's File检查它是否是文件
【发布时间】:2014-04-14 10:12:46
【问题描述】:

我编写了非常小的代码来检查它是否是文件。我期待我应该得到“是”的打印,但我没有得到。我犯了什么愚蠢的错误吗?

os.listdir(os.getcwd()+"/../py")
a = ['a.py', 'a.pyc']
>>> for _a in a:
...  if os.path.isfile(_a):
...     print "yes"

【问题讨论】:

  • 将文件的路径作为输入(您的文件似乎不在当前工作目录中)。

标签: python python-2.7 file


【解决方案1】:

您需要提供一个完整路径;您只提供了一个相对路径,因此 Python 在当前工作目录中查找这些文件,并且在 os.getcwd() 中没有名为 a.py 的文件。

首先将另一个目录的路径存储在一个变量中:

path = os.path.abspath('../py')
for name in os.listdir(path):
    if os.path.isfile(os.path.join(path, name):
        print "yes", name, "is a file!"

我使用os.path.abspath() 而不是os.getcwd() 将您的相对路径转换为规范化的绝对​​路径,并使用os.path.join() 然后使用该路径为os.listdir() 返回的名称列表构造绝对路径。

【讨论】:

    【解决方案2】:

    a.py 在当前目录中查找名为a.py 的文件。您的代码似乎暗示您应该提供路径 (../py?)

    例如:

    >>> for _a in a:
    ...  if os.path.isfile(os.path.join('../py', _a)):
    ...     print "yes"
    

    【讨论】:

      猜你喜欢
      • 2010-11-08
      • 2015-11-11
      • 2013-08-08
      • 1970-01-01
      • 2014-09-21
      • 1970-01-01
      • 2016-06-11
      • 2023-03-21
      • 1970-01-01
      相关资源
      最近更新 更多