pythonpathtreeappendmkdirs

Python os.makedirs to recreate path


I want to go through every line in a text file of existing paths and file names, divide the strings into drive, path, and filename. Then what I would like to do is copy the files with their paths to a new location - either a different drive or append to an existing file tree (i.e., if S:\A\B\C\D\E\F.shp is the original file. I wish to append it to the new location as C:\users\visc\A\B\C\D\E\F.shp

Due to my poor programming skills, I continue to receive the error:

File "C:\Users\visc\a\b.py", line 28, in <module>
     (destination) = os.makedirs( pathname, 0755 );

Here is my code:

import os,sys, shutil

## Open the file with read only permit
f = open('C:/Users/visc/a/b/c.txt')

destination = ('C:/Users/visc')
# read line by line
for line in f:

     line = line.replace("\\\\", "\\")
     #split the drive and path using os.path.splitdrive
     (drive, pathname) = os.path.splitdrive(line)
     #split the path and fliename using os.path.split
     (pathname, filename) = os.path.split(pathname)
#print the stripped line
     print line.strip()
#print the drive, path, and filename info
     print('Drive is %s Path is %s and file is %s' % (drive, pathname, filename))

     (destination) = os.makedirs( pathname, 0755 );
     print "Path is Created"

Thank you


Solution

  • I guess you want something like

    os.makedirs(os.path.join(destination, pathname), 0755 )
    

    if you want to connect the file paths given by pathname with the new destination given by destination. Your code currently tries to create a file in the same place as before (at least it looks like this - can't say for sure since I don't know what's in the file you're reading and what is your current directory).

    If you assign the result of the call to os.makedirs() to destination (the parentheses are as useless as the semicolon in that line), you effectively set destination to None since os.makedirs() doesn't actually return anything. And you're not using it to construct your new path.