Splitting path strings into drive, path and file name parts Splitting path strings into drive, path and file name parts python python

Splitting path strings into drive, path and file name parts


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:

  • 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 :)


You can use os.path.splitdrive() to get the drive and then path.split() the remainder.

## Open the file with read only permitf = 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))