18

私はPythonとコーディング全般に不慣れです。各行にパス名を持つテキスト ファイルから読み込もうとしています。テキスト ファイルを 1 行ずつ読み取り、行の文字列をドライブ、パス、ファイル名に分割したいと思います。

これまでの私のコードは次のとおりです。

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一般的に使用することをお勧めします)
  • 括弧は必要ありません - os.path.splitdrive(path) はタプルを返し、これは自動的に解凍されます
  • fileは標準名前空間のクラスの名前であり、おそらく上書きしないでください:)
于 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 に答える