Vis*_*ral 17 python split path filepath
我是python和编码的新手.我试图从一个文本文件中读取每行都有路径名.我想逐行读取文本文件,并将行字符串拆分为驱动器,路径和文件名.
这是我到目前为止的代码:
import os,sys, arcpy
## Open the file with read only permit
f = open('C:/Users/visc/scratch/scratch_child/test.txt')
for line in f:
(drive,path,file) = os.path.split(line)
print line.strip()
#arcpy.AddMessage (line.strip())
print('Drive is %s Path is %s and file is %s' % (drive, path, file))
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
File "C:/Users/visc/scratch/simple.py", line 14, in <module>
(drive,path,file) = os.path.split(line)
ValueError: need more than 2 values to unpack
Run Code Online (Sandbox Code Playgroud)
当我只想要路径和文件名时,我没有收到此错误.
Man*_*ert 31
你需要先使用os.path.splitdrive:
with open('C:/Users/visc/scratch/scratch_child/test.txt') as f:
for line in f:
drive, path = os.path.splitdrive(line)
path, filename = os.path.split(path)
print('Drive is %s Path is %s and file is %s' % (drive, path, filename))
Run Code Online (Sandbox Code Playgroud)
笔记:
with语句确保文件在块结束时关闭(文件也在垃圾收集器吃它们时关闭,但使用with通常是好的做法file 是标准命名空间中的类的名称,您可能不应该覆盖它:)您可以使用os.path.splitdrive()来获取驱动器,然后使用path.split()来获取其余部分.
## Open the file with read only permit
f = open('C:/Users/visc/scratch/scratch_child/test.txt')
for line in f:
(drive, path) = os.path.splitdrive(line)
(path, file) = os.path.split(path)
print line.strip()
print('Drive is %s Path is %s and file is %s' % (drive, path, file))
Run Code Online (Sandbox Code Playgroud)