将路径字符串拆分为驱动器,路径和文件名部分

问题描述:

我是python和编码的新手。我正尝试从每行上都有路径名的文本文件读取。我想逐行阅读文本文件,并将行字符串拆分为驱动器,路径和文件名。将路径字符串拆分为驱动器,路径和文件名部分

这里是我的代码至今:

我得到以下错误:

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 

我没有收到这个错误时,我只希望的路径和文件名。

您需要使用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通常是很好的做法
  • 你不需要使用方括号ETS - os.path.splitdrive(路径)返回一个元组,而这将让自动解压缩
  • file是标准命名空间类的名字,你可能不应该覆盖它:)
+0

您好,我收到以下输出:驱动器是路径是“S:\ Entourage \ GIS \ HemloBelt \ Claims和文件是Entourage_Claims_Master.shp”,所以不是我所期望的。每行都格式化如下:“S:\ Entourage \ GIS \ HemloBelt \ Claims \ Entourage_Claims_Master.shp”, – Visceral

+0

我想你是在一台Windows机器上。在'drive,path = ...'之前,添加'line = line.replace(“\\”,“/”)'用正斜杠替换反斜杠,看看这是否有效。 –

+0

我发现它为什么表现得如此。我在原始文本文件中引用了每行字符串的引号。 – Visceral

您可以使用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)) 
+0

感谢花时间回答。 – Visceral

+0

嗨Jordanm,这是我的屏幕上打印的:'code'“S:\ Entourage \ GIS \ HemloBelt \ Claims \ Entourage_Claims_Master.shp”, Drive is Path is“S:\ Entourage \ GIS \ HemloBelt \ Claims”文件是Entourage_Claims_Master.shp“,不完全是我想到的。 – Visceral