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

这是我的代码:

导入操作系统、系统、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

3 回答 3

5

您需要做的是在调用之前检查文件夹是否存在,makedirs()或者在文件夹已经存在时处理发生的异常。在 Python 中,处理异常更常规一些,所以改变你的makedirs()行:

try:
    (destination) = os.makedirs( pathname, 0755 )
except OSError:
    print "Skipping creation of %s because it exists already."%pathname

在尝试创建文件夹之前检查文件夹的策略称为“Look Before You Leap”或 LBYL;处理预期错误的策略是“请求宽恕比许可更容易”或 EAFP。EAFP 的优点是它可以正确处理文件夹由检查和makedirs()调用之间的另一个进程创建的情况。

于 2012-05-10T18:44:10.753 回答
3

我猜你想要类似的东西

os.makedirs(os.path.join(destination, pathname), 0755 )

如果您想将 给出的文件路径pathname与 给出的新目标连接起来destination。您的代码当前尝试在与以前相同的位置创建文件(至少看起来像这样 - 不能肯定地说,因为我不知道您正在阅读的文件中的内容以及当前目录是什么)。

如果将调用结果分配给os.makedirs()to destination(括号与该行中的分号一样无用),则实际上设置destinationNonesinceos.makedirs()实际上不会返回任何内容。而且你没有用它来构建你的新路径。

于 2012-05-10T18:12:48.920 回答
2

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

os.makedirs(名称,模式=0o777,exist_ok=False)

如果您有幸被允许使用 Python 3,这可能是一个更好(更安全)的选择。

于 2015-09-14T15:08:06.213 回答