路径和文件名部分

路径和文件名部分

本文介绍了将路径字符串分为驱动器,路径和文件名部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to python and coding in general. I am trying to read from a text file which has path names on each line. I would like to read the text file line by line and split the line strings into drive, path and file name.

到目前为止,这是我的代码:

Here is my code thus far:

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

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

I do not receive this error when I only want the path and file name.

推荐答案

您需要先使用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是标准名称空间中的类的名称,您可能不应该覆盖它:)
  • the with statement makes sure the file is closed at the end of the block (files also get closed when the garbage collector eats them, but using with is generally good practice
  • 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 :)

这篇关于将路径字符串分为驱动器,路径和文件名部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 13:09