Python 将路径字符串拆分为驱动器、路径和文件名部分
我对python和一般的编码都是新手。我试图从每行都有路径名的文本文件中读取。我想逐行读取文本文件,并将行字符串拆分为驱动器、路径和文件名 以下是我迄今为止的代码:Python 将路径字符串拆分为驱动器、路径和文件名部分,python,path,split,filepath,Python,Path,Split,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.s
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))
我得到以下错误:
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
文件“C:/Users/visc/scratch/simple.py”,第14行,在
(驱动器、路径、文件)=os.path.split(行)
ValueError:需要2个以上的值才能解包
当我只需要路径和文件名时,我没有收到此错误。您可以使用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))
您需要首先使用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))
注:
with
语句确保文件在块结束时关闭(垃圾收集器吃掉文件时文件也会关闭,但使用with
通常是一种良好的做法)
- 您不需要括号-os.path.splitdrive(path)返回一个元组,它将自动解压缩
file
是标准命名空间中类的名称,您可能不应该覆盖它:)
感谢您抽出时间回答。你好,Jordanm,这是我屏幕上打印的内容:code
“S:\Entourage\GIS\hemloblt\Claims\Entourage\u Claims\u Master.shp”,驱动器路径是“S:\Entourage\GIS\hemloblt\Claims,文件是Entourage\u Claims\u Master.shp”,这与我的想法不太一致。嗨,Nk,我收到了以下输出:驱动器的路径是“S:\Entourage\GIS\HemloBelt\Claims,文件是Entourage\u Claims\u Master.shp”,所以与我预期的不太一样。每行的格式如下:“S:\Entourage\GIS\hemloblt\Claims\Entourage\u Claims\u Master.shp”,我想您是在windows机器上。在drive,path=…
之前,添加line=line.replace(“\\”,“/”)
将反斜杠替换为正斜杠,看看这是否奏效。我发现了它为什么会这样。在我的原始文本文件中,每行字符串周围都有引号。