Python中的os.makedirs用于重新创建路径

3
我希望能够遍历一个文本文件中每一行现有路径和文件名的字符串,将其分为驱动器、路径和文件名。然后我想要做的是将这些带路径的文件复制到一个新位置——可以是不同的驱动器,也可以是附加到现有文件树中(即如果S:\A\B\C\D\E\F.shp是原始文件,则将其附加到新位置C:\users\visc\A\B\C\D\E\F.shp)。
由于我的编程技能差,我一直收到以下错误:
File "C:\Users\visc\a\b.py", line 28, in <module>
     (destination) = os.makedirs( pathname, 0755 );

这是我的代码:

import os,sys,shutil

## Open the file with read only permit
f = open('C:/Users/visc/a/b/c.txt')

destination = ('C:/Users/visc')
# read line by line
for line in f:

     line = line.replace("\\\\", "\\")
     #split the drive and path using os.path.splitdrive
     (drive, pathname) = os.path.splitdrive(line)
     #split the path and fliename using os.path.split
     (pathname, filename) = os.path.split(pathname)
#print the stripped line
     print line.strip()
#print the drive, path, and filename info
     print('Drive is %s Path is %s and file is %s' % (drive, pathname, filename))

     (destination) = os.makedirs( pathname, 0755 );
     print "Path is Created"

谢谢您


4
你没有包含实际的错误信息。 - Tim Pietzcker
抱歉,这是我的完整错误信息:Traceback (most recent call last): File "C:\Users\visc\a\b.py", line 28, in <module> (destination) = os.makedirs( pathname, 0755 ); File "C:\Python26\ArcGIS10.0\lib\os.py", line 157, in makedirs mkdir(name, mode) WindowsError: [Error 183] Cannot create a file when that file already exists: '\\A\\B\\C\\D\\E' - Visceral
3个回答

5
您需要做的是在调用makedirs()之前检查文件夹是否存在,或者处理如果文件夹已经存在时发生的异常。在Python中,更常规的做法是处理异常,因此请更改您的makedirs()行:
try:
    (destination) = os.makedirs( pathname, 0755 )
except OSError:
    print "Skipping creation of %s because it exists already."%pathname

在尝试创建文件夹之前先检查文件夹的策略被称为“先看再跳”或LBYL; 处理预期错误的策略是“宁愿请求原谅,也不要事先获得许可”或EAFP。 EAFP的优点是它正确处理了在检查和调用之间由另一个进程创建文件夹的情况。


错误发生是因为他在错误的位置构建目录 - 捕获异常只会掩盖问题。 - Tim Pietzcker
1
我通常避免掩盖特定类型的所有异常。最好这样做:except OSError, e: if e.errno != errno.EEXIST: raise - btimby

3
我猜你想要类似这样的东西:
os.makedirs(os.path.join(destination, pathname), 0755 )

如果您想将pathname给定的文件路径连接到destination给定的新目标。您的代码当前尝试在与之前相同的位置创建文件(至少看起来是这样的-不能确定因为我不知道您正在读取的文件内容以及您的当前目录是什么)。
如果您将对os.makedirs()的调用结果分配给destination(括号和该行中的分号一样无用),则实际上将destination设置为None,因为os.makedirs()实际上并不返回任何内容。而且您没有使用它来构建新路径。

抱歉,这是我的完整错误信息:File"C:\Users\visc\a\b.py",第28行,在<module>中(destination)=os.makedirs(pathname,0755); File"C:\Python26\ArcGIS10.0\lib\os.py",第157行,在makedirs中mkdir(name,mode)WindowsError:[Error 183]无法创建文件,因为该文件已经存在:'\\A\\B\\C\\D\\E' - Visceral

2

Python 3.2增加了一个可选参数exist_ok:

os.makedirs(name, mode=0o777, exist_ok=False)

如果您可以使用Python 3,那么这可能是更好(更安全)的选择。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接