18

我是 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

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

4

2 回答 2

32

您需要先使用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通常是一个好习惯
  • you don't need the brackets - os.path.splitdrive(path) returns a tuple, and this will get automatically unpacked
  • file is the name of a class in the standard namespace and you should probably not overwrite it :)
于 2012-05-08T22:28:04.137 回答
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))
于 2012-05-08T22:24:05.653 回答