gpt4 book ai didi

python - os.path.isdir() 和 os.path.isfile() 都在脚本中返回 False 但在 Python 控制台中返回 True(就像它们应该的那样)

转载 作者:行者123 更新时间:2023-12-05 05:11:01 24 4
gpt4 key购买 nike

我正在尝试使用 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

最佳答案

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

关于python - os.path.isdir() 和 os.path.isfile() 都在脚本中返回 False 但在 Python 控制台中返回 True(就像它们应该的那样),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55980486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com