Vis*_*ral 3 python tree append path mkdirs
我想浏览现有路径和文件名的文本文件中的每一行,将字符串分成驱动器,路径和文件名.那么我想要做的是将文件及其路径复制到新位置 - 不同的驱动器或附加到现有的文件树(即,如果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 );
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
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"
Run Code Online (Sandbox Code Playgroud)
谢谢
您需要做的是在调用之前检查文件夹是否存在,makedirs()或者处理文件夹已存在时发生的异常.在Python中,处理异常更常规,所以改变你的makedirs()行:
try:
(destination) = os.makedirs( pathname, 0755 )
except OSError:
print "Skipping creation of %s because it exists already."%pathname
Run Code Online (Sandbox Code Playgroud)
在尝试创建文件夹之前检查文件夹的策略称为"在你跳跃前看"或LBYL; 处理预期错误的策略是"更容易请求宽恕而不是许可"或EAFP.EAFP的优点是它可以正确处理文件夹由检查和makedirs()调用之间的另一个进程创建的情况.
| 归档时间: |
|
| 查看次数: |
15905 次 |
| 最近记录: |