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

时间:2012-05-08 22:11:05

标签: 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.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

当我只想要路径和文件名时,我没有收到此错误。

2 个答案:

答案 0 :(得分:30)

您需要先使用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是标准命名空间中类的名称,您可能不应该覆盖它:)

答案 1 :(得分:6)

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