python - 属性错误 : 'module' object has no attribute 'exist'

标签 python directory python-os

我想检查文件是否存在,以及它是否为我使用 mkdir 创建的文件夹提供了下一个更高的数字。 我以某种方式得到了 Error: AttributeError: 'module' object has no attribute 'exist' 我不明白为什么那个 os 函数对我不起作用。有什么想法吗?

import os
map_name="Example.png"
wk_dir = os.path.dirname(os.path.realpath('__file__'))
dir_name=os.path.splitext(os.path.basename(map_name))[0]

for n in range(0,200):
    m=n+1
    if os.path.exist(wk_dir + "/" + dir_name + "_%s_%dx%d_%d" % (a, resolution, resolution,n)):
        os.mkdir(wk_dir + "/" + dir_name + "_%s_%dx%d_%d" % (a, resolution, resolution,m))
    break

最佳答案

你的问题是一个错字。应该是

os.path.exists(wk_dir + "/" + dir_name + "_%s_%dx%d_%d" % (a, resolution, resolution,n))

代替

os.path.exist(wk_dir + "/" + dir_name + "_%s_%dx%d_%d" % (a, resolution, resolution,n))

请注意,如果有任何名称作为参数传递的内容,无论是文件还是目录,os.path.exists 都会返回 true。

检查文件是否存在:

import os
if os.path.isfile("~/myfile"):
    print("this file exists!")
else:
    print("file not found!")

检查目录是否存在:

import os
if os.path.isdir("~/mydir"):
    print("this directory exists!")
else:
    print("directory not found!")

关于python - 属性错误 : 'module' object has no attribute 'exist' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52457552/

相关文章:

python - 使用 `map` 构造多个命名元组

python - Django |加入的路径位于基本路径组件 {% static img.thumbnail.url %} 之外,错误 400 with whitenoise

linux - 比较 Linux 中两个目录与​​第三个目录中文件的存在情况

python - 如何在GAE中的ndb模型中创建随机默认值?

python - 将 openpyxl 与 lambda 结合使用

python - Windows 与 Linux 文件模式

python - plotly :从hoverlabels隐藏 `null`

python - 如何在 Tkinter 中将二维数组从一个类传递到另一个类?

java - 如何为特定目录创建监视器?

java - 如何在不遵循符号链接(symbolic link)的情况下递归删除文件夹?