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))
I get the following error:
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.
You need to use os.path.splitdrive
first:
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))
Notes:
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 practicefile
is the name of a class in the standard namespace and you should probably not overwrite it :)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With