【问题标题】:os.path.isdir() and os.path.isfile() both returning False in script but return True (like they should) in the Python consoleos.path.isdir() 和 os.path.isfile() 都在脚本中返回 False,但在 Python 控制台中返回 True(就像它们应该的那样)
【发布时间】:2019-05-04 15:51:07
【问题描述】:

我正在尝试使用foros 模块来运行文件名列表,将itemtype 变量相应地更改为“FILE”或“DIRECTORY”,然后将其打印出来。当我尝试在 Python 控制台中执行此操作时,效果很好。但是,当在我的脚本中运行几乎相同的代码时,isdir()isfile() 函数都返回 false。

我在控制台中试试这个:

>>> import os
>>> files = os.listdir()
>>> print(files)
['namebydate.py', 'order.bat', 'storebydate.py', 'test', '__pycache__']
>>> for i in files:
...  itemtype=''
...  if os.path.isdir(i):
...   itemtype='DIRECTORY'
...  elif os.path.isfile(i):
...   itemtype='FILE'
...
...  print('{itemtype}'.format(itemtype=itemtype))
...
FILE
FILE
FILE
DIRECTORY
DIRECTORY
>>>

而且效果很好。 但是当我的脚本运行并进入它的等价物时:

for i in files:
    itemtype = ''
    if os.path.isdir(i):
        itemtype = 'DIRECTORY'
    elif os.path.isfile(i):
        itemtype = 'FILE'
    print('({current}/{total}) [{itemtype}] {name}'.format(
        current=str(files.index(i)+1),
        total=len(files),
        itemtype=itemtype,
        name=i))

函数返回false,将itemtype值保留为空字符串,输出变为:

Listing...
(1/4) [] testdir
(2/4) [] testdoc1.txt
(3/4) [] testdoc2.txt
(4/4) [] testdoc3.txt

在这种情况下,预期的结果应该是:

Listing...
(1/4) [DIRECTORY] testdir
(2/4) [FILE] testdoc1.txt
(3/4) [FILE] testdoc2.txt
(4/4) [FILE] testdoc3.txt

【问题讨论】:

  • 我运行了你的代码,运行良好。

标签: python for-loop


【解决方案1】:

isdirisfile 需要 pathlistdir 返回 name。换句话说,要检查isdirisfile,您应该在文件名之前附加路径。例如:

import os

dir = '/'
files = os.listdir(dir)
os.path.isdir(os.path.join(dir, files[0])
os.path.isfile(os.path.join(dir, files[0])

【讨论】:

  • 啊,成功了!仍然不确定为什么它在控制台中起作用,但在没有它的情况下不能在脚本中起作用,但将其添加到脚本中似乎可以解决问题。
  • 不确定,但您是否在根目录中运行了控制台?
  • 它在脚本使用的同一目录中运行。
  • 很奇怪。因为如果我运行os.path.isfileos.path.isdir 来检查根目录中的项目,它就可以工作。因为在这种情况下路径等于名称具体
猜你喜欢
  • 2017-08-02
  • 1970-01-01
  • 2014-10-21
  • 2016-03-03
  • 2020-02-12
  • 2019-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多