Python on Windows 10:os.rename() 找不到 os.path.exists() 找到的文件?
Python on Windows 10: os.rename() cannot find a file that os.path.exists() finds?
我想知道 os.rename()
:尽管 os.path.exists()
说该文件存在,但 os.rename()
说找不到它。这是代码片段:
try:
if (os.path.exists(sourcePath)):
print('Safe: %s does exist!' % sourcePath)
os.rename (sourcePath, newPath)
except Exception as e:
print('Error renaming "%s":' % sourcePath)
raise e
运行 这个在名为 Y:\home\Paul\PaulsBilder\images\..\import\batch012-05 Neuruppin-05 - 0 2.JPG
的文件上产生了以下输出:
Safe: Y:\home\Paul\PaulsBilder\images\..\import\batch012-05 Neuruppin-05 - 0 2.JPG does exist!
Error renaming "Y:\home\Paul\PaulsBilder\images\..\import\batch012-05 Neuruppin-05 - 0 2.JPG":
Traceback (most recent call last):
:
WindowsError: [Error 3] Das System kann den angegebenen Pfad nicht finden
(German Windows: "The system cannot find the specified path.") 我现在一直在使用这个片段一段时间没有问题,但可能从来没有在带空格的文件名上......但是,当我替换空格时带下划线,文件名仍然找不到。
肯定还有其他地方不对,但是什么?
编辑:删除 /../
组件(通过将 os.normpath()
包裹起来)没有帮助。
非常感谢Skycc,您说的很对:错误发生是因为新路径名的目录不存在。傻我。
这个有效 - 确保 os.makedirs()
只被调用一次:
try:
if (os.path.exists(sourcePath)):
print('Safe: %s does exist!' % sourcePath)
(head, tail) = os.path.split(newPath) # @UnusedVariable
if (not os.path.exists(head)):
os.makedirs(head)
os.rename(sourcePath, newPath)
except Exception as e:
print('Error renaming "%s" to "%s":' % (sourcePath, newPath))
raise e
我想知道 os.rename()
:尽管 os.path.exists()
说该文件存在,但 os.rename()
说找不到它。这是代码片段:
try:
if (os.path.exists(sourcePath)):
print('Safe: %s does exist!' % sourcePath)
os.rename (sourcePath, newPath)
except Exception as e:
print('Error renaming "%s":' % sourcePath)
raise e
运行 这个在名为 Y:\home\Paul\PaulsBilder\images\..\import\batch012-05 Neuruppin-05 - 0 2.JPG
的文件上产生了以下输出:
Safe: Y:\home\Paul\PaulsBilder\images\..\import\batch012-05 Neuruppin-05 - 0 2.JPG does exist!
Error renaming "Y:\home\Paul\PaulsBilder\images\..\import\batch012-05 Neuruppin-05 - 0 2.JPG":
Traceback (most recent call last):
:
WindowsError: [Error 3] Das System kann den angegebenen Pfad nicht finden
(German Windows: "The system cannot find the specified path.") 我现在一直在使用这个片段一段时间没有问题,但可能从来没有在带空格的文件名上......但是,当我替换空格时带下划线,文件名仍然找不到。
肯定还有其他地方不对,但是什么?
编辑:删除 /../
组件(通过将 os.normpath()
包裹起来)没有帮助。
非常感谢Skycc,您说的很对:错误发生是因为新路径名的目录不存在。傻我。
这个有效 - 确保 os.makedirs()
只被调用一次:
try:
if (os.path.exists(sourcePath)):
print('Safe: %s does exist!' % sourcePath)
(head, tail) = os.path.split(newPath) # @UnusedVariable
if (not os.path.exists(head)):
os.makedirs(head)
os.rename(sourcePath, newPath)
except Exception as e:
print('Error renaming "%s" to "%s":' % (sourcePath, newPath))
raise e