os.walk/list
so i am trying to add md5 checksum calc to my file copy stuff, to make sure the source and dest. are same file. i implemented it fine with the single file copy part. something like : for files in sourcepath: f1=file(files ,'rb') try: shutil.copy2(files, os.path.join(destpath,os.path.basename(files))) except: print "error file" f2=file(os.path.join(destpath,os.path.basename(files)), 'rb') truth = md5.new(f1.read()).digest() == md5.new(f2.read()).digest() if truth == 0: print "file copy error" this worked swimmingly. i moved on to my backupall function, something like for (path, dirs, files) in os.walk(source): #os.walk drills down thru all the folders of source for fname in dirs: currentdir = destination+leftover try: os.mkdir(os.path.join(currentdir,fname),0755) except: print "error folder" for fname in files: leftover = path.replace(source, '') currentdir = destination+leftover f1=file(files ,'rb') try: shutil.copy2(os.path.join(path,fname), os.path.join(currentdir,fname)) f2 = file(os.path.join(currentdir,fname,files)) except: print "error file" truth = md5.new(f1.read()).digest() == md5.new(f2.read()).digest() if truth == 0: print "file copy error" but here, "fname" is a list, not a single file.i didn't really want to spend a lot of time on the md5 part. thought it would be an easy add- on. i don't really want to write the file names out to a list and parse through them one a time doing the calc, but it sounds like i will have to do something like that. -- http://mail.python.org/mailman/listinfo/python-list
Re: os.walk/list
yes i agree breaking stuff into smaller chunks is a good way to do it. even were i to do something like def safe_copy() f1=file(files ,'rb') f2 = file(os.path.join(currentdir,fname,files)) truth = md5.new(f1.read()).digest() == md5.new(f2.read()).digest() if truth == 0: print "file copy error" that would probably work for the single file copy functions. but would still breakdown during the for ...os.walk(), again because "fname" is a list there, and the crypto functions work 1 file at a time. even changing crypto functions wouldn't change that. -- http://mail.python.org/mailman/listinfo/python-list
python time
I'm working on a script that will run all the time. at time specified in a config file, will kick-off a backup. problem is, its not actually starting the job. the double while loop runs, the first comparing date works. the second for hour/min does not. #python file import os,string,,time,getpass,ConfigParser from datetime import * from os.path import join, getsize from time import strftime,localtime config = ConfigParser.ConfigParser() config.read("config.ini") source = config.get("myvars", "source") destination = config.get("myvars", "destination") date = config.get("myvars", "date") time = config.get("myvars", "time") str_time=strftime("%H:%M",localtime()) while datetime.now().weekday() == int(date): while str_time == time: print "do it" #config file #change the time variable to "now"+a min or two to observe #this needs to be where ever the actual python script is [myvars] #only set source if you want it to be different source: c:\users\jon destination: \\mothera\jon\ #what day of the week to perform backup?where Monday is 0 and Sunday is 6 date: 6 #time to start time: 21:02 -- http://mail.python.org/mailman/listinfo/python-list
Re: python time
On Mar 20, 10:09 pm, Dave Angel wrote: > On 01/-10/-28163 02:59 PM, ecu_jon wrote: > > > > > I'm working on a script that will run all the time. at time specified > > in a config file, will kick-off a backup. > > problem is, its not actually starting the job. the double while loop > > runs, the first comparing date works. the second for hour/min does > > not. > > > #python file > > import os,string,,time,getpass,ConfigParser > > from datetime import * > > from os.path import join, getsize > > from time import strftime,localtime > > > config = ConfigParser.ConfigParser() > > config.read("config.ini") > > source = config.get("myvars", "source") > > destination = config.get("myvars", "destination") > > date = config.get("myvars", "date") > > time = config.get("myvars", "time") > > str_time=strftime("%H:%M",localtime()) > > > while datetime.now().weekday() == int(date): > > while str_time == time: > > print "do it" > > You're comparing two objects in that inner while-loop, but since they > never change, they'll never match unless they happen to start out as > matched. > > you need to re-evaluate str_time each time through the loop. Make a > copy of that statement and put it inside the loop. > > You probably don't want those loops to be comparing to ==, though, since > if you start this script on some other day, it'll never loop at all. > Also, it'd be good to do some form of sleep() function when you're > waiting, so you don't bog the system down with a busy-loop. > > DaveA i guess im just having a hard time creating something like check if go condition, else sleep the double while loops take 12% cpu usage on my machine so this is probably unacceptable. also the sleep command does not like me : >>> from datetime import * >>> from time import strftime,localtime,sleep >>> time.sleep(3) Traceback (most recent call last): File "", line 1, in time.sleep(3) AttributeError: type object 'datetime.time' has no attribute 'sleep' >>> here it is updated with the hour/min check fixed. #updated python code import os,string,time,getpass,md5,ConfigParser from datetime import * from os.path import join, getsize from time import strftime,localtime,sleep config = ConfigParser.ConfigParser() config.read("config.ini") date = config.get("myvars", "date") time = config.get("myvars", "time") while datetime.now().weekday() == int(date): str_time=strftime("%H:%M",localtime()) while str_time == time: print "do it" -- http://mail.python.org/mailman/listinfo/python-list
Re: python time
On Mar 20, 10:48 pm, ecu_jon wrote: > On Mar 20, 10:09 pm, Dave Angel wrote: > > > > > On 01/-10/-28163 02:59 PM, ecu_jon wrote: > > > > I'm working on a script that will run all the time. at time specified > > > in a config file, will kick-off a backup. > > > problem is, its not actually starting the job. the double while loop > > > runs, the first comparing date works. the second for hour/min does > > > not. > > > > #python file > > > import os,string,,time,getpass,ConfigParser > > > from datetime import * > > > from os.path import join, getsize > > > from time import strftime,localtime > > > > config = ConfigParser.ConfigParser() > > > config.read("config.ini") > > > source = config.get("myvars", "source") > > > destination = config.get("myvars", "destination") > > > date = config.get("myvars", "date") > > > time = config.get("myvars", "time") > > > str_time=strftime("%H:%M",localtime()) > > > > while datetime.now().weekday() == int(date): > > > while str_time == time: > > > print "do it" > > > You're comparing two objects in that inner while-loop, but since they > > never change, they'll never match unless they happen to start out as > > matched. > > > you need to re-evaluate str_time each time through the loop. Make a > > copy of that statement and put it inside the loop. > > > You probably don't want those loops to be comparing to ==, though, since > > if you start this script on some other day, it'll never loop at all. > > Also, it'd be good to do some form of sleep() function when you're > > waiting, so you don't bog the system down with a busy-loop. > > > DaveA > > i guess im just having a hard time creating something like > check if go condition, > else sleep > > the double while loops take 12% cpu usage on my machine so this is > probably unacceptable. > also the sleep command does not like me : > >>> from datetime import * > > >>> from time import strftime,localtime,sleep > >>> time.sleep(3) > > Traceback (most recent call last): > File "", line 1, in > time.sleep(3) > AttributeError: type object 'datetime.time' has no attribute 'sleep' > > > > here it is updated with the hour/min check fixed. > #updated python code > import os,string,time,getpass,md5,ConfigParser > from datetime import * > from os.path import join, getsize > from time import strftime,localtime,sleep > > config = ConfigParser.ConfigParser() > config.read("config.ini") > date = config.get("myvars", "date") > time = config.get("myvars", "time") > > while datetime.now().weekday() == int(date): > str_time=strftime("%H:%M",localtime()) > while str_time == time: > print "do it" i think this is what you are talking about except that the time.sleep just does not work. even changing "from time import strftime,localtime" to "from time import strftime,localtime,sleep" does not do it. #python code import os,string,time,getpass,md5,ConfigParser from datetime import * from os.path import join, getsize from time import strftime,localtime config = ConfigParser.ConfigParser() config.read("config.ini") date = config.get("myvars", "date") time = config.get("myvars", "time") a=1 while a>0: if datetime.now().weekday() == int(date): str_time=strftime("%H:%M",localtime()) if str_time == time: print "do it" time.sleep(58) -- http://mail.python.org/mailman/listinfo/python-list
Re: python time
so then why does this not work ? from datetime import datetime from os.path import join, getsize import time,os,string,getpass,md5,ConfigParser from time import strftime,localtime config = ConfigParser.ConfigParser() config.read("config.ini") date = config.get("myvars", "date") time = config.get("myvars", "time") #print "date is ",date , " time is ",time a=1 while a>0: #import time time.sleep(2) if datetime.now().weekday() == int(date): str_time=strftime("%H:%M",localtime()) print "do it" Traceback (most recent call last): File "I:\college\spring11\capstone-project\time-test.py", line 25, in time.sleep(2) AttributeError: 'str' object has no attribute 'sleep' >>> if i uncomment the import time line in the while loop it works. boggle... -- http://mail.python.org/mailman/listinfo/python-list
Re: python time
i see. i was using time as a variable name , messing it all up.im not going to post the whole backup script here, but here are a few lines that i changed to make it work. from datetime import datetime from os.path import join, getsize import time,os,string,getpass,md5,ConfigParser from time import strftime,localtime hrmin = config.get("myvars", "hrmin") #was time =, this is what did it. while a>0: if datetime.now().weekday() == int(date): str_time=strftime("%H:%M",localtime()) if str_time == hrmin: print "do it" os.system(cmd) time.sleep(5)#will prolly want to change to to 30 or higher for release file. -- http://mail.python.org/mailman/listinfo/python-list
string to path problem
i am writing a basic backup program for my school. so they wanted the possibility to be able to set source/destination from a config file. my source/destination was fine before, i would build it up with functions, like 1 that got the user-name, and put it all together with os.path.join. but if they set a source in the config file to something like c:\users\jon\backup python tries to read from c:\\users\\jon\ \backup, and throws out a read permission (because it doesn't exist ...). i am not sure what to do at this point. i have look at the docs for string, and os. . i cant os.path.join anything if they give me an absolute path. here is a bit of the code import os,string,fnmatch,shutil,time,getpass,md5,ConfigParser from datetime import * from os.path import join, getsize config = ConfigParser.ConfigParser() config.read("config.ini") source = config.get("myvars", "source") destination = config.get("myvars", "destination") helptext = config.get("myvars", "helptext") def weekChoice(): dateNum = datetime.now().day if dateNum <=7: week = 1 elif (dateNum >= 8) and (dateNum <= 14): week = 2 elif (dateNum >= 15) and (dateNum <= 21): week = 3 elif dateNum > 22: week = 4 else: print "error" return week def destination1(): global destination username = getpass.getuser() week = weekChoice() weekstr = "week"+str(week) destination1 = os.path.join("//mothera","jon","week1") #where // mothera is a samba server on the network return destination1 print "source :",source destination = destination1() shutil.copy2(source, destination) here is some of config.ini [myvars] source:c:\users\jon\backup destination: -- http://mail.python.org/mailman/listinfo/python-list
Re: string to path problem
On Apr 4, 12:17 am, Chris Rebert wrote: > On Sun, Apr 3, 2011 at 8:30 PM, ecu_jon wrote: > > i am writing a basic backup program for my school. so they wanted the > > possibility to be able to set source/destination from a config file. > > my source/destination was fine before, i would build it up with > > functions, like 1 that got the user-name, and put it all together with > > os.path.join. but if they set a source in the config file to something > > like c:\users\jon\backup python tries to read from c:\\users\\jon\ > > \backup, and throws out a read permission (because it doesn't > > exist ...). > > Please give the exact error message and full exception traceback that > you're getting. > > Cheers, > Chris Traceback (most recent call last): File "I:\college\spring11\capstone-project\testing1.py", line 39, in shutil.copy2(source1, destination) File "C:\Python27\lib\shutil.py", line 127, in copy2 copyfile(src, dst) File "C:\Python27\lib\shutil.py", line 81, in copyfile with open(src, 'rb') as fsrc: IOError: [Errno 13] Permission denied: 'c:\\users\\jon\\backup' i have permission to c:\users\jon\* but c:\\* obviously does not exist. -- http://mail.python.org/mailman/listinfo/python-list
Re: string to path problem
On Apr 4, 5:06 am, Kushal Kumaran wrote: > On Mon, Apr 4, 2011 at 9:48 AM, ecu_jon wrote: > > On Apr 4, 12:17 am, Chris Rebert wrote: > >> On Sun, Apr 3, 2011 at 8:30 PM, ecu_jon wrote: > >> > i am writing a basic backup program for my school. so they wanted the > >> > possibility to be able to set source/destination from a config file. > >> > my source/destination was fine before, i would build it up with > >> > functions, like 1 that got the user-name, and put it all together with > >> > os.path.join. but if they set a source in the config file to something > >> > like c:\users\jon\backup python tries to read from c:\\users\\jon\ > >> > \backup, and throws out a read permission (because it doesn't > >> > exist ...). > > >> Please give the exact error message and full exception traceback that > >> you're getting. > > >> Cheers, > >> Chris > > Traceback (most recent call last): > > File "I:\college\spring11\capstone-project\testing1.py", line 39, in > > > > shutil.copy2(source1, destination) > > File "C:\Python27\lib\shutil.py", line 127, in copy2 > > copyfile(src, dst) > > File "C:\Python27\lib\shutil.py", line 81, in copyfile > > with open(src, 'rb') as fsrc: > > IOError: [Errno 13] Permission denied: 'c:\\users\\jon\\backup' > > > i have permission to c:\users\jon\* > > but c:\\* obviously does not exist. > > The extra backslashes in the string literal are there to "escape" the > required backslashes. This is required because the backslash > character is used to introduce certain special characters in strings, > such as tabs and newlines. The actual string does not contain the > extra backslashes. This is documented in extensive detail in the > language > reference:http://docs.python.org/reference/lexical_analysis.html#string-literals. > But you might want to start with the > tutorial:http://docs.python.org/tutorial/introduction.html#strings > > Example: > > > > >>> s = 'c:\\users\\jon\\backup' > >>> print s > c:\users\jon\backup > > Is c:\users\jon\backup a directory? The shutil.copyfile function will > only copy a file. There is a shutil.copytree that will copy an entire > directory tree. > > -- > regards, > kushal well i changed a few minor things in the bigger problem, and c:\users \jon\backup as the source worked fine. now to test it on winxp, where the default has a space in the name. -- http://mail.python.org/mailman/listinfo/python-list
homedir, file copy
hello, i am trying to work with windows homedirectory as a starting point for some kind of file copy command. i'm testing this on a win7 box so my home is c:\Users\jon\ here is the code snippet i am working on: import os homedir = os.path.expanduser('~') try: from win32com.shell import shellcon, shell homedir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0) except ImportError: homedir = os.path.expanduser("~") print homedir print os.listdir(homedir+"\\backup\\") homedir.replace("" , "\\") print homedir shutil.copy (homedir+"\\backup\\", homedir+"\\backup2\\") output looks like: C:\Users\jon ['test1.txt', 'test2.txt'] C:\Users\jon Traceback (most recent call last): File "D:\spring 11\capstone-project\date.py", line 43, in shutil.copy (homedir+"\\backup\\", homedir+"\\backup2\\") File "C:\Python27\lib\shutil.py", line 116, in copy copyfile(src, dst) File "C:\Python27\lib\shutil.py", line 81, in copyfile with open(src, 'rb') as fsrc: IOError: [Errno 2] No such file or directory: 'C:\\Users\\jon\\backup\ \' why is there still two \\ in the pathfor the copy command? -- http://mail.python.org/mailman/listinfo/python-list
Re: homedir, file copy
On Jan 30, 3:55 pm, r wrote: > On Jan 30, 2:44 pm, ecu_jon wrote: > > > shutil.copy (homedir+"\\backup\\", homedir+"\\backup2\\") > > TIP: Use os.path.join(x,y, z*) > > > why is there still two \\ in the pathfor the copy command? > > I always convert my paths to use a single '/' instead of '\\'. Just > makes life that much easier! what does this mean? Use os.path.join(x,y, z*) what is the x,y,z? -- http://mail.python.org/mailman/listinfo/python-list
Re: homedir, file copy
ok now i get permission denied import os homedir = os.path.expanduser('~') try: from win32com.shell import shellcon, shell homedir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0) except ImportError: homedir = os.path.expanduser("~") print homedir print os.listdir(homedir+"\\backup\\") #homedir.replace("" , "\\") #print homedir backupdir1 = os.path.join(homedir, "backup") backupdir2 = os.path.join(homedir, "backup2") shutil.copy (backupdir1, backupdir2) -- http://mail.python.org/mailman/listinfo/python-list
Re: homedir, file copy
On Jan 30, 7:09 pm, MRAB wrote: > On 30/01/2011 23:43, ecu_jon wrote: > > > ok now i get permission denied > > > import os > > homedir = os.path.expanduser('~') > > try: > > from win32com.shell import shellcon, shell > > homedir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0) > > > except ImportError: > > homedir = os.path.expanduser("~") > > print homedir > > print os.listdir(homedir+"\\backup\\") > > #homedir.replace("" , "\\") > > #print homedir > > backupdir1 = os.path.join(homedir, "backup") > > backupdir2 = os.path.join(homedir, "backup2") > > shutil.copy (backupdir1, backupdir2) > > shutil.copy(...) copies files, not directories. You should use > shutil.copytree(...) instead. i will, closer towards the end. just wanted to get past the naming stuff, the problem above. right now i just want to see it move files from 1 place to another. i had copytree in before, and will go back to that for final version. im working on a backup program, and copytree looks yummy. still no idea why getting permission denied. -- http://mail.python.org/mailman/listinfo/python-list
Re: homedir, file copy
On Jan 30, 7:19 pm, Dave Angel wrote: > On 01/-10/-28163 02:59 PM, ecu_jon wrote: > > > ok now i get permission denied > > > import os > > homedir = os.path.expanduser('~') > > try: > > from win32com.shell import shellcon, shell > > homedir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0) > > > except ImportError: > > homedir = os.path.expanduser("~") > > print homedir > > print os.listdir(homedir+"\\backup\\") > > #homedir.replace("" , "\\") > > #print homedir > > backupdir1 = os.path.join(homedir, "backup") > > backupdir2 = os.path.join(homedir, "backup2") > > shutil.copy (backupdir1, backupdir2) > > You forgot to include the error traceback. > > So, is homedir/backup a file, or is it a directory? If you're trying to > copy whole directories, you might want to look at copytree instead. > > If you're not sure, you could use > os.isfile() > > to check. If that's false, then shutil.copy() can't work. Similarly, > if the destination is a readonly file, you'd get some error. > > DaveA today's date is : 30 week chosen is : 4 C:\Users\jon ['test1.txt', 'test2.txt'] Traceback (most recent call last): File "D:\spring 11\capstone-project\date.py", line 45, in shutil.copy (backupdir1, backupdir2) File "C:\Python27\lib\shutil.py", line 116, in copy copyfile(src, dst) File "C:\Python27\lib\shutil.py", line 81, in copyfile with open(src, 'rb') as fsrc: IOError: [Errno 13] Permission denied: 'C:\\Users\\jon\\backup' -- http://mail.python.org/mailman/listinfo/python-list
Re: homedir, file copy
On Jan 30, 7:34 pm, rantingrick wrote: > On Jan 30, 5:43 pm, ecu_jon wrote: > > > ok now i get permission denied > > [...] > > > shutil.copy (backupdir1, backupdir2) > > I must stress the importance of proper testing before ever running > code that manipulates files! So many things can go wrong. Of course > you are just copying files here and not deleting them however you must > always be in the habit of treating files like explosives. And frankly > you're being quite nonchalant with this very naive approach to coding > and complete lack of testing. > > When handling files always test, test, test. Never actually move, > copy, or delete until you are *absolutely* sure no failures will > occur. I will always do test runs that print out the action but DO NOT > actually DO the action, like... > > Copying files: > -- from: C:\\somefile1 > to: C:\\blah\\somefile1 > -- from: C:\\somefile2 > to: C:\\blah\\somefile2 > -- from: C:\\somefile3 > to: C:\\blah\\somefile3 > -- etc... > > Once my test runs are bug free i can try to move or delete *one* file > from some test set. Once that is bug free then i will try the code on > many files of a test set, and ONLY THEN on the real thing. I guarantee > if you keep manipulating files in such a haphazard way you will live > to regret it! not nonchalant. i know i will ned to do testing and whatnot. just personally, i like to build stuff one concept at a time. for example, i had a problem with the homedir and peopel here helped me with that. now i have permissions problem, and an swer will likely meeerge. once i know how to copy a file, ill work on testing. like isfile and permissions. i know that has to be done. i guess its that you want tests before moves , and thats fine. since i have only ever had 1 python class, and basically learning this whole thing from scratch, i need to do things 1 step at a time. so now any thoughts on why i cannot write to my own homedir? -- http://mail.python.org/mailman/listinfo/python-list
Re: homedir, file copy
On Jan 30, 8:25 pm, MRAB wrote: > On 31/01/2011 00:18, ecu_jon wrote: > > > > > On Jan 30, 7:09 pm, MRAB wrote: > >> On 30/01/2011 23:43, ecu_jon wrote: > > >>> ok now i get permission denied > > >>> import os > >>> homedir = os.path.expanduser('~') > >>> try: > >>> from win32com.shell import shellcon, shell > >>> homedir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0) > > >>> except ImportError: > >>> homedir = os.path.expanduser("~") > >>> print homedir > >>> print os.listdir(homedir+"\\backup\\") > >>> #homedir.replace("" , "\\") > >>> #print homedir > >>> backupdir1 = os.path.join(homedir, "backup") > >>> backupdir2 = os.path.join(homedir, "backup2") > >>> shutil.copy (backupdir1, backupdir2) > > >> shutil.copy(...) copies files, not directories. You should use > >> shutil.copytree(...) instead. > > > i will, closer towards the end. > > just wanted to get past the naming stuff, the problem above. > > right now i just want to see it move files from 1 place to another. > > i had copytree in before, and will go back to that for final version. > > im working on a backup program, and copytree looks yummy. > > > still no idea why getting permission denied. > > The path given by backupdir1 is a directory, so you're trying to use > shutil.copy(...) to copy a directory. > > The reason that it's complaining about permissions is that shutil.copy > is trying to open the source file (look at the traceback) so that it > can copy the file's contents, but it's not a file, it's a directory. > > CPython is written in C, so it's probably the underlying C library > which is reporting it as a permissions problem instead of a "that's not > a file!" problem. :-) as for testing i was planning on using something like this http://docs.python.org/library/shutil.html scroll down to 10.10.1.1 -- http://mail.python.org/mailman/listinfo/python-list
files,folders,paths
i have a samba server at home (acting as my test environment) with one of the 'shares' mounted as v: on my windows box. inside of that are 4 folders week[1-4]. i have created c:\users\name\backup , and put a few files/folders in there to test with. please ignore the wxpython parts of the script, the last 1/3, that part is functional. initial test was looking good. (in the code, ver011 source1, destination1) coping files/ folders and not clobbering files. going to version 12a, it seems like it is trying to copy the files under the folder, before making the folder. or doing the copy2 part before the copytree part. i dont know why it works on ver011, and not in ver12a, the only difference being the destination. http://thanksforallthefish.endofinternet.net/ facbac-011.py">facbac 011 http://thanksforallthefish.endofinternet.net/ facbac-012a.py">facbac 012a Traceback (most recent call last): File "I:\college\spring11\capstone-project\facbac-012a.py", line 161, in button1Click backupall() File "I:\college\spring11\capstone-project\facbac-012a.py", line 81, in backupall shutil.copy2(filesource, filedest1) File "C:\Python27\lib\shutil.py", line 127, in copy2 copyfile(src, dst) File "C:\Python27\lib\shutil.py", line 82, in copyfile with open(dst, 'wb') as fdst: IOError: [Errno 2] No such file or directory: 'V:\\week2\\configs\ \apache2.conf' here, apache2.conf = c:\users\name\backup\config\apache2.conf trying to copy to v:\week2\config\apache2.conf but there is no v:\week2\config as it has not made the config folder yet i think the problem might be the \\ in the destination name. -- http://mail.python.org/mailman/listinfo/python-list
Re: files,folders,paths
i just tried changing that in ver12a, still get IOError: [Errno 2] No such file or directory: 'V:\\week2\\configs\ \apache2.conf' good catch tho as that is needed. thanks. weekchoice is used to pick week 1-4. really jsut returns 1-4. i plan to do full weekly backups with another script. getusername i was using when i was trying to build the path as part of a unc path. isdir/isfile did not play well with that. homedir returns the users home directory. works in xp,7, and linux. source and destination should be self explanatory. the backupall() gets called from clicking the button. for now its the meat and potatoes im working on. it is trying to recursively copy files/folders from source to dest. the for ... os.walk line digs through the backup folder. i use os.chgdir , os.getcwd and leftover to build the path for file/folder names on dest. basically start at c: \users\name\backup\somefolder and end with just somefolderadded to dest. if os.path.isdir(fname): checks if it is a folder. copytree is a recursive folder copy. elif os.path.isfile(fname): if it is a file. copy2 copies files and metadata. class MyForm(wx.Frame): and down is wxpython, that works. ( tho i will take suggestions but i know this is not the right forum to as questions for that part) -- http://mail.python.org/mailman/listinfo/python-list
Re: files,folders,paths
On Feb 13, 8:17 am, Dave Angel wrote: > On 01/-10/-28163 02:59 PM, ecu_jon wrote: > > > > > i just tried changing that in ver12a, still get > > IOError: [Errno 2] No such file or directory: 'V:\\week2\\configs\ > > \apache2.conf' > > good catch tho as that is needed. thanks. > > weekchoice is used to pick week 1-4. really jsut returns 1-4. i plan > > to do full weekly backups with another script. > > getusername i was using when i was trying to build the path as part of > > a unc path. isdir/isfile did not play well with that. > > homedir returns the users home directory. works in xp,7, and linux. > > source and destination should be self explanatory. > > the backupall() gets called from clicking the button. for now its the > > meat and potatoes im working on. it is trying to recursively copy > > files/folders from source to dest. the for ... os.walk line digs > > through the backup folder. i use os.chgdir , os.getcwd and leftover to > > build the path for file/folder names on dest. basically start at c: > > \users\name\backup\somefolder and end with just somefolderadded to > > dest. > > if os.path.isdir(fname): checks if it is a folder. copytree is a > > recursive folder copy. > > elif os.path.isfile(fname): if it is a file. copy2 copies files and > > metadata. > > class MyForm(wx.Frame): and down is wxpython, that works. ( tho i will > > take suggestions but i know this is not the right forum to as > > questions for that part) > > I haven't tried to run your script, since much of it is Windows > dependent, and I'm on Linux. So observations are just by inspection. > > I suspect your problem is that you're trying to change drives as well as > directories. In Windows, there's a current directory on each drive, > that Windows remembers. So changing directories on a different drive > doesn't mean what you might think it does. I'd recommend doing no > chdir()'s at all, and using only absolute paths. > > But I see other complications or maybe risks in the code, concentrating > on function backupall(). You're using os.walk(), which walks through a > whole tree of files. But then when you encounter a directory, you're > doing a copytree(). So you'll be copying the same files many-many times. > > Similarly, you have logic for copying a single file, but you invoke it > on a name from dirlist, which is a list of directories, so the isfile() > probably never fires. > > os.walk() assumes the current directory is unchanged during its run. > See: http://docs.python.org/library/os.html#module-os > "walk() never changes the current directory, and assumes that its > caller doesn’t either." > > You're not copying the files at the top level at all; you don't process > the list called 'files', while you could probably safely copy *only* the > files. > > Your name manipulations in this same function look risky, using replace > when you presumably know that a string is either at the begin or end. > > In function homeDir(), you never return the value calculated in the try > block. If you don't get an exception, you return None. > > DaveA first let me say, you guys are helping me and i thank you for that. i do not want to sound confrontational. i have don my best to make this os agnostic. yes i know, right now in 21a, destination2 is windows specific. that's mostly because os.path.isdir() and unc paths do not play well with each other. the os.chdir() came about out of need to build relative path names. some examples : c:\users\name\backup\ #win7 c:\docs and settings\name\app data\backup\ #winxp /home/name/backup #linux and mac i wanted to start from 'backup' in all these cases. my destination is going to look like \\servername\username\week[1-4] yes os.walk goes thru the whole tree (under backup in my case). the os.chdir() under the for line in def backupall(): basically juct chages folders to whever the os.walk() is. it never tried to change to a different drive letter.the folder copy thing, these 2 lines if os.path.isdir(fname): #if it is a folder if not os.path.isdir(destination+leftover): #and id dont exist on dest drive work on version 011, determine if its a folder, then if it exists. only copy if both: it is a folder, and not exist on destination. this "return homedir" needed to be moved 1 tab left. copy error from random code to functionalizing parts. good catch thanks. dirlsit, returns the names of folders and files. i was using a different method http://thanksforallthefish.endofinternet.net/date-linuxversion.py try version 11 for yourself. in your home directory (ie: /home/name) make a backup folder, put
Re: files,folders,paths
"Please don't dump code on us and tell us to ignore parts of it. We're offering our time and experience without charging you, the least you can do is take the time to eliminate the irrelevant parts of the code yourself, and show us the smallest piece of code which demonstrates the problem. " i appreciate your opinion. im fairly new here so i might not get etiquette right.i only asked you all to ignore it for 2 reasons, it's wxpython to not really targets to the crowd, and it does not interact with the python parts. other than simply as a means to call the functions. i could chop off the bottom and replace it with a functname(), it would be the same for my question. i know backslashes are special. there a special pain in my #$%. without a windows environment, you would have to change destination2 significantly to try it out. but like i said above you can try version 11 in a linux environment. i know config does not exist, for some reason the isfolder check is passing it off saying it exists, when it does not. then moving on to the isfiles parts. tries to copy a folder deep files with no folder to write to, and fails. i jsut don't understand why the folder check is not working right in version 12a. and destination2, IS basically the difference between 11 and 12a. it should be the only difference. the isfile difference someone else pointed out i have since changed that, stil lsame problem. and again thanks all for time/trouble. -- http://mail.python.org/mailman/listinfo/python-list
Re: files,folders,paths
On Feb 13, 5:11 pm, Tim Roberts wrote: > ecu_jon wrote: > > >i know backslashes are special. there a special pain in my #$%. > >without a windows environment, you would have to change destination2 > >significantly to try it out. but like i said above you can try version > >11 in a linux environment. > > If they are a pain in your #$%, then don't use them. You can use forward > slashes everywhere in Windows, except when typing commands at the command > prompt. ALL of the Windows file system APIs accept forward slashes. > -- > Tim Roberts, t...@probo.com > Providenza & Boekelheide, Inc. can you give an example of how to build a folder name, maybe as a string, with parts of it as variables, that have to be strung together. like x = "//servername/+variable+"/"+variable+"/" when i did something liek that the end result string was like //servername/folder/folder\file and i got an error -- http://mail.python.org/mailman/listinfo/python-list
Re: files,folders,paths
On Feb 13, 6:39 pm, Ben Finney wrote: > ecu_jon writes: > > can you give an example of how to build a folder name, maybe as a > > string, with parts of it as variables, that have to be strung > > together. like x = "//servername/+variable+"/"+variable+"/" > > import os.path > > infile_path = os.path.join(["//servername", start_dir, other_dir]) > > Read the documentation for ‘os.path.join’. It's fundamental if you're > working with filesystem paths. > > > when i did something liek that the end result string was like > > //servername/folder/folder\file and i got an error > > That path should work on MS Windows. If you want us to comment on the > error, you'll need to show the code here *and* the error traceback. > > -- > \ “If this is your first visit to the USSR, you are welcome to | > `\ it.” —hotel room, Moscow | > _o__) | > Ben Finney here take a look. http://thanksforallthefish.endofinternet.net/testing.py the output looks like folder to copy = Mothera\\jon\week2 file to copy: C:\Users\jon\backup\configs\apache2.conf Mothera\\jon \week2\configs\apache2.conf folder to copy = Mothera\\jon\week2\configs #some lines ommited for brevity. -- http://mail.python.org/mailman/listinfo/python-list
Re: files,folders,paths
On Feb 13, 8:29 pm, Ben Finney wrote: > ecu_jon writes: > > here take a look. > >http://thanksforallthefish.endofinternet.net/testing.py > > I think you're confusing yourself by shoving lots of experimental lines > into a large program and not isolating the problem. I see that you are > trying lots of different ways of doing the same thing, and commenting > some lines out arbitrarily. > > Instead, focus on the issue that's causing you confusion: constructing a > filesystem path and testing whether it exists. > > Make a *minimal* program that shows the problem you're having. Post it > *here* (that's why it's important that it be minimal), along with the > exact error traceback you get from Python when you run it. > > Once you have something minimal that we, too, can run, we can comment > better on its behaviour. > > -- > \ “Members of the general public commonly find copyright rules | > `\ implausible, and simply disbelieve them.” —Jessica Litman, | > _o__) _Digital Copyright_ | > Ben Finney this thing evolved i piece a a time. i got help from the wxpython people, and now that code has been stable for weeks. the function weekChoice came after talking to 2 CS grad studenst for 2 hours. deciding how to decide what week to pick. it seems to be solid. was picking week 1 up till 12:02 when i tested it on the 8th, then went to week 2. getusername probably should be unfunctionalized, and maybe dropped completely. homeDir is good on the 3 differnt platforms i have tested it on, linux, xp and 7. Ubuntu returned /home/name, 7 returned c:\Users\name \, xp returned c:\docs and settings\name\app data\ or something close to that. in version 011, source1 and destination1 worked fine. selectivly coping files or folders as needed. backupall has been volatile, but relatively stable last 2 weeks. in version 011, it does the if not folder and file detection. in version 12a, it does not. all of the functions cascade so im not really sure how i could cut something out, with out serious rewrite. i already did shrink it by gutting the wxpython parts. after uncommenting the 2 lines shutil.copytree(os.getcwd(), destination+leftover) shutil.copy2(filesource, filedest1) i get this as an traceback folder to copy = Mothera\\jon\week2 Traceback (most recent call last): File "I:\college\spring11\capstone-project\testing.py", line 86, in backupall() File "I:\college\spring11\capstone-project\testing.py", line 73, in backupall shutil.copytree(os.getcwd(), destination+leftover) File "C:\Python27\lib\shutil.py", line 174, in copytree os.makedirs(dst) File "C:\Python27\lib\os.py", line 150, in makedirs makedirs(head, mode) File "C:\Python27\lib\os.py", line 150, in makedirs makedirs(head, mode) File "C:\Python27\lib\os.py", line 150, in makedirs makedirs(head, mode) File "C:\Python27\lib\os.py", line 157, in makedirs mkdir(name, mode) WindowsError: [Error 161] The specified path is invalid: '' -- http://mail.python.org/mailman/listinfo/python-list
Re: files,folders,paths
On Feb 13, 8:48 pm, Dave Angel wrote: > (You forgot to include the list in your response, and you neglected to > properly quote the message you were replying to. That makes it quite > hard to separate your remarks from mine) > > On 02/13/2011 07:19 PM, jon hayes wrote: > > > c:\users\name\backup\ #win7 > >> c:\docs and settings\name\app data\backup\ #winxp > >> /home/name/backup #linux and mac > > > In what way do those imply a need for chdir() ? What's wrong with > > os.path.join() ? > > the only commonality is the \backup > > the chdir() is there to build the path name of the destination. > > so c:\users\name\backup\folder1\folder2\file3 > > in my code, doing the substution. > > Well, since chdir() is illegal inside the os.walk() context and > unnecesary, I suggest you debug your original technique. Build the > names with os.path.join(), as I've suggested twice before, and others > have mentioned as well. > > > > > these 3 lines > > os.chdir(path) > > cwd = os.getcwd() > > leftover = cwd.replace(source, '') > > in this case leftover = \folder1\folder2 > > which gets added to the path for the destination in > > shutil.copytree(os.getcwd(), destination+leftover) > > > i looked at the relpath, it did not do exacly what i wanted. in version 11 > > of the code this works out well. > > I can't see how os.path.relpath() would be useful here. > > > > > "And I quote from facbac-012a.py: > > os.chdir("v:")" > > i don't understand. is this a question? > > It is in context. If you read my message, I had just quoted you saying > you did not change drive letters. > > > > > "I suggest you actually try writing a simple loop using os.walk to just > > display the names of all the files in and under a specified directory. > > Then maybe you'll understand what path, dirs, and files actually are." > > i started with that. look at the attached file, date-linuxversion.py. > > the relative paths are not, quite, right. > > Well file you enclosed shows that you don't understand os.walk(). So > learn it before trying to use it in a more complex setting. Why would > you use the following sequence? > > filestring = str(files) > filestring = filestring.strip("[") > filestring = filestring.strip("]") > filestring = filestring.strip("'") > > This is no way to process a list of filenames. > > > the thing with the copytree is, the line above is sopposed to check whether > > that folder exists. if it does not exist at all, then why not copy the > > whole thing? > > same sort of thing with files. if not exist then do copy. that way nothing > > should get clobbered. > > this is the observed behavior in version 11. > > Why not copy the whole tree? Because once the code works, you'll be > copying it many times. > > DaveA if i do not change the directory how do i get the relative folder path. for example, starting with c:\users\name\backup\folder1\folder2\file as the oswalk drills down through the folders, when it is in the 'folder2' folder, if you do something like print dirs it would output just 'folder2' not the whole path or any of the other parts. so how do i know where to write this to on the destination relative to \\servername\username\week[1-4]\ or possibly that folder mounted as a drive in windows as v:\week[1-4]\ ? how do i build the output folder name. bear in mind it works great in version 011. i spent weeks, and tried maybe 7 different other ways before going down this path, so to speak. i thought about using a list. or an array. but you wouldnt know when oswalk starts bak from top level to go int another folder. let me think if i can say it another way. ... i think what you guys want me to do the osjoin on is this line destination = r"Mothera\\"+username+"\\"+weekstr or shutil.copytree(os.getcwd(), destination+leftover) please clarify. -- http://mail.python.org/mailman/listinfo/python-list
Re: files,folders,paths
this is a reply to both Dave Angel and Ben Finney. this version of testing i think incorperates what you guys are saying. http://thanksforallthefish.endofinternet.net/ testing1.py">testin1.py except maybe the os.join.path in the last function. here is the traceback Traceback (most recent call last): File "I:\college\spring11\capstone-project\testing.py", line 88, in backupall() File "I:\college\spring11\capstone-project\testing.py", line 84, in backupall shutil.copy2(filesource, filedest1) File "C:\Python27\lib\shutil.py", line 127, in copy2 copyfile(src, dst) File "C:\Python27\lib\shutil.py", line 82, in copyfile with open(dst, 'wb') as fdst: IOError: [Errno 2] No such file or directory: '//Mothera/week2\\jonI:\ \college\\spring11\\capstone-project\\changelog.txt' it looks like it needs os.walk and the other for line to dig through the folders. this being the whole path I:\\college\\spring11\\capstone-project\\changelog.txt of source. -- http://mail.python.org/mailman/listinfo/python-list
Re: files,folders,paths
On Feb 14, 12:12 am, Ben Finney wrote: > ecu_jon writes: > > On Feb 13, 8:29 pm, Ben Finney wrote: > > > Instead, focus on the issue that's causing you confusion: > > > constructing a filesystem path and testing whether it exists. > > > > Make a *minimal* program that shows the problem you're having. Post it > > > *here* (that's why it's important that it be minimal), along with the > > > exact error traceback you get from Python when you run it. > > > > Once you have something minimal that we, too, can run, we can comment > > > better on its behaviour. > > > this thing evolved i piece a a time. > > I don't doubt it. But clearing up confusion over what a big wad of code > does is best done by trying to isolate the problem into a small piece of > code. > > > i got help from the wxpython people, and now that code has been stable > > for weeks. > > > the function weekChoice came after talking to 2 CS grad studenst for 2 > > hours. deciding how to decide what week to pick. it seems to be solid. > > was picking week 1 up till 12:02 when i tested it on the 8th, then > > went to week 2. > > This all sounds as though you're doing ball-of-mud programming: keep > throwing more code at the program, and whatever sticks must stay there > forever without understanding what it's doing. > > That's a bad idea. I hope you can already see why. > > Really, please make a new, minimal, complete example that still exhibits > the specific confusing behaviour, and *post it in a message* (not at a > URL), so we can see the problem in isolation. If it's more than a dozen > lines, it's doing too much for the problem you're talking about here. > > -- > \ “We cannot solve our problems with the same thinking we used | > `\ when we created them.” —Albert Einstein | > _o__) | > Ben Finney well it seems not to be the difference between versions 11,12,12a. it works great on my linux box. i get all these errors on the windows boxes. i think it has to do with the folder name, and strings etc. got to se if i can use os.join.path for the whole naming. -- http://mail.python.org/mailman/listinfo/python-list
Re: files,folders,paths
i think i got it. my dirlist wasn't the right way to go, i needed to iterate thu what oswalk was giving me in dirs, and files. not bruteforce strip to a string. i have been starting at an early version and a later version for the last 4 hours or so, and i think i have it this only handles the folders. i wanted to try out the logic before i doubled up and parsed files too. substitute this in for the backup function. and for now the source and destination functions are in this to. ill clean it up once i test it more. backupdir = os.path.join(homedir, "backup") remotedir = os.path.join(homedir, "backup2") weekstr = "week"+str(week) remotedirweek = os.path.join(remotedir, weekstr) print '' for (path, dirs, files) in os.walk(backupdir): print "current path is : ",path print "current dir is : ",dirs print "current files are: ",files for fname in dirs: os.chdir(path) leftover = os.getcwd().replace(backupdir, '') print "leftover is:",leftover print "remotedirweek is:",remotedirweek currentdir1 = remotedirweek+leftover if not os.path.isdir(currentdir1): print "currentdir1:",currentdir1 print "i should copy teh folderz",os.path.join(currentdir1,fname) shutil.copytree(os.getcwd(),os.path.join(currentdir1,fname)) -- http://mail.python.org/mailman/listinfo/python-list
Re: files,folders,paths
On Feb 14, 4:43 am, Dave Angel wrote: > On 01/-10/-28163 02:59 PM, ecu_jon wrote: > > > > > this is a reply to both Dave Angel and Ben Finney. this version of > > testing i think incorperates what you guys are saying. > > http://thanksforallthefish.endofinternet.net/ > > testing1.py">testin1.py > > except maybe the os.join.path in the last function. > > here is the traceback > > Traceback (most recent call last): > > File "I:\college\spring11\capstone-project\testing.py", line 88, in > > > > backupall() > > File "I:\college\spring11\capstone-project\testing.py", line 84, in > > backupall > > shutil.copy2(filesource, filedest1) > > File "C:\Python27\lib\shutil.py", line 127, in copy2 > > copyfile(src, dst) > > File "C:\Python27\lib\shutil.py", line 82, in copyfile > > with open(dst, 'wb') as fdst: > > IOError: [Errno 2] No such file or directory: '//Mothera/week2\\jonI:\ > > \college\\spring11\\capstone-project\\changelog.txt' > > > it looks like it needs os.walk and the other for line to dig through > > the folders. > > this being the whole path > > I:\\college\\spring11\\capstone-project\\changelog.txt of source. > > Simplify the code. > > def weekChoice() > return 1 + (datetime.now().day -1) // 7 #weeks go from 1 to 5 > > def backupall(): > source = source1() > destination = destination2() > print "copy tree ", source, destination > if os.path.exists(destination): > if os.path.isdir(destination): > shutil.rmtree(destination) > else: > os.unlink(destination) > shutil.copytree(source, destination) > return > > All that nonsense with curdir was messing up your thinking. > > I'm not going to try to debug your destination2() function, but I would > point out that when you use os.path.join(), please let it do the work > for you. It takes any number of arguments, and those arguments should > not have extra slashes or backslashes in them. The leading slashes are > okay for the first node, if you want a unc. > > It would have been much easier if you had made source and destination > arguments to the backupall() function. It then might have become clear > that it's simply copytree(), with the extra requirement of deleting > whatever used to be there. > > Now if you aren't allowed to delete what was already there, then you > can't use copytree, and need to start over with os.walk(). > > DaveA and dest2 was me trying different ways to write to the sever, unc or mounted drive. that's for later :P i missed this "as missing parent directories." shutil.copytree(src, dst[, symlinks=False[, ignore=None]])¶ Recursively copy an entire directory tree rooted at src. The destination directory, named by dst, must not already exist; it will be created as well as missing parent directories. so for testing i did the copy once. deleted the files in top folder, and deleted a folder deeper in. gave error when tried to copytree the deeper in folder. is there something like mkdir? -- http://mail.python.org/mailman/listinfo/python-list
Re: files,folders,paths
On Feb 14, 4:43 am, Dave Angel wrote: > On 01/-10/-28163 02:59 PM, ecu_jon wrote: > > > > > this is a reply to both Dave Angel and Ben Finney. this version of > > testing i think incorperates what you guys are saying. > > http://thanksforallthefish.endofinternet.net/ > > testing1.py">testin1.py > > except maybe the os.join.path in the last function. > > here is the traceback > > Traceback (most recent call last): > > File "I:\college\spring11\capstone-project\testing.py", line 88, in > > > > backupall() > > File "I:\college\spring11\capstone-project\testing.py", line 84, in > > backupall > > shutil.copy2(filesource, filedest1) > > File "C:\Python27\lib\shutil.py", line 127, in copy2 > > copyfile(src, dst) > > File "C:\Python27\lib\shutil.py", line 82, in copyfile > > with open(dst, 'wb') as fdst: > > IOError: [Errno 2] No such file or directory: '//Mothera/week2\\jonI:\ > > \college\\spring11\\capstone-project\\changelog.txt' > > > it looks like it needs os.walk and the other for line to dig through > > the folders. > > this being the whole path > > I:\\college\\spring11\\capstone-project\\changelog.txt of source. > > Simplify the code. > > def weekChoice() > return 1 + (datetime.now().day -1) // 7 #weeks go from 1 to 5 > > def backupall(): > source = source1() > destination = destination2() > print "copy tree ", source, destination > if os.path.exists(destination): > if os.path.isdir(destination): > shutil.rmtree(destination) > else: > os.unlink(destination) > shutil.copytree(source, destination) > return > > All that nonsense with curdir was messing up your thinking. > > I'm not going to try to debug your destination2() function, but I would > point out that when you use os.path.join(), please let it do the work > for you. It takes any number of arguments, and those arguments should > not have extra slashes or backslashes in them. The leading slashes are > okay for the first node, if you want a unc. > > It would have been much easier if you had made source and destination > arguments to the backupall() function. It then might have become clear > that it's simply copytree(), with the extra requirement of deleting > whatever used to be there. > > Now if you aren't allowed to delete what was already there, then you > can't use copytree, and need to start over with os.walk(). > > DaveA i thought i had it. i think im going to sleep on it. here is what im working with right now. jsut trying to make folders stuff work. def backupall(): week = weekChoice() weekstr = "week"+str(week) source = source1() #was backupdir destination = destination1() #was remotedir #destinationweek = os.path.join(destination, weekstr) for (path, dirs, files) in os.walk(source): for fname in dirs: os.chdir(path) leftover = os.getcwd().replace(source, '') #print "leftover is:",leftover currentdir = destination+leftover if not os.path.isdir(currentdir): print "leftover is:",leftover print "currentdir1:",currentdir print "i should copy teh folderz",os.path.join(currentdir,fname) os.mkdir(os.path.join(currentdir,fname),0755) it is not making the top level folder, then tries to create deeper folders and fails. part of the traceback. os.mkdir(os.path.join(currentdir,fname),0755) WindowsError: [Error 3] The system cannot find the path specified: 'C:\ \Users\\jon\\backup2\\week2\\configs\\squid_files' -- http://mail.python.org/mailman/listinfo/python-list
Re: files,folders,paths
well i think i will close this out. redid recursive foldering now for 3rd or 4th time. below script works from a windows to another folder (destination1) or a unc path(destination2). i tried it on my linux box, and the error deals with writing to a remote smb share. i think if it was mounted somewhere, it would work fine with something like dest1, but changing the path(or mounting the remote drive to backup2 for the lazy ). #!/usr/bin/python import wx,os,string,fnmatch,shutil,tempfile,time,getpass from datetime import * from os.path import join, getsize def weekChoice(): #week = 0 dateNum = datetime.now().day if dateNum <=7: week = 1 elif (dateNum >= 8) and (dateNum <= 14): week = 2 elif (dateNum >= 15) and (dateNum <= 21): week = 3 elif dateNum > 22: week = 4 else: print "error" return week def getusername(): username = getpass.getuser() return username def homeDir(): homedir = os.path.expanduser('~') try: from win32com.shell import shellcon, shell homedir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0) except ImportError: homedir = os.path.expanduser("~") return homedir def source1(): week = weekChoice() homedir = homeDir() #changed backupdir to source source = os.path.join(homedir, "backup") return source def destination1(): week = weekChoice() homedir = homeDir() remotedir = os.path.join(homedir, "backup2") weekstr = "week"+str(week) destination = os.path.join(remotedir, weekstr) return destination def destination2(): username = getusername() week = weekChoice() weekstr = "week"+str(week) destination = os.path.join("//Mothera",username,weekstr) #need to mount the smb share somewhere return destination def backupall(): week = weekChoice() weekstr = "week"+str(week) source = source1() destination = destination2() # change this around to suit needs for (path, dirs, files) in os.walk(source): for fname in dirs: leftover = path.replace(source, '') #print "leftover = ",leftover currentdir = destination+leftover #print "currentdir = ",currentdir try: #print "dest folder to make",os.path.join(currentdir,fname) os.mkdir(os.path.join(currentdir,fname),0755) except: print "error folder" for fname in files: leftover = path.replace(source, '') #print "leftover = ",leftover currentdir = destination+leftover #print "currentdir = ",currentdir try: #print "dest file to make",os.path.join(currentdir,fname) shutil.copy2(os.path.join(path,fname),os.path.join(currentdir,fname)) except: print "error file" backupall() -- http://mail.python.org/mailman/listinfo/python-list
file/folder naming
im trying to use wxpython to get a source file/files, then a destination folder to write them to. the file and folder picker works. the problem is, actually copying (actually shutil.copy2() ). i get an except error, as if the destination file name is not correct. looking at the print lines the destination looks right. i used os.path.join to join the folder path and the filebasename. i can hear it now, that this belongs on the wxpython page, and i will be posting there as well. but, im fairly certain its something in this "for files in sourcepath:" import wx,os,string,shutil,getpass from datetime import * def backupfiles(): dialog = wx.FileDialog(None, "Choose a source file :", style=1 | wx.MULTIPLE ) if dialog.ShowModal() == wx.ID_OK: sourcepath = dialog.GetPaths() else: dialog.Destroy() dialog = wx.DirDialog(None, "Choose a destination directory :", style=1 ) if dialog.ShowModal() == wx.ID_OK: destpath = dialog.GetPath() else: dialog.Destroy() print "sourcepath is :",sourcepath print "destpath is :",destpath for files in sourcepath: print "destpath is :",os.path.join(destpath,os.path.basename(files)) try: shutil.copy2(sourcepath, os.path.join(destpath,os.path.basename(files))) except: print "error file" class MyForm(wx.Frame): """make a frame, inherits wx.Frame""" def __init__(self): # create a frame, no parent, default to wxID_ANY wx.Frame.__init__(self, None, wx.ID_ANY, title="FacBac", pos=(300, 150), size=(500, 200)) self.SetBackgroundColour("purple") panel = wx.Panel(self, wx.ID_ANY) self.title1 = wx.StaticText(panel, wx.ID_ANY, "Backup") self.title2 = wx.StaticText(panel, wx.ID_ANY, "Restore") self.button1 = wx.Button(panel, id=-1, label='Backup ALL') self.button1.Bind(wx.EVT_BUTTON, self.button1Click) self.button1.SetToolTip(wx.ToolTip("this will backup your whole folder")) gridSizer = wx.GridSizer(rows=4, cols=2, hgap=5, vgap=5) gridSizer.Add(self.title1, 0, wx.ALL|wx.ALIGN_CENTER, 5) gridSizer.Add(self.title2, 0, wx.ALL|wx.ALIGN_CENTER, 5) gridSizer.Add(self.button1, 0, wx.ALL|wx.EXPAND, 5) topSizer = wx.BoxSizer(wx.VERTICAL) topSizer.Add(gridSizer, 0, wx.ALL|wx.EXPAND, 5) self.SetSizeHints(500,200,500,200) panel.SetSizer(topSizer) topSizer.Fit(self) def button1Click(self, event): self.button1.SetLabel("Doing Backup") backupfiles() self.button1.SetLabel("Backup All") if __name__ == "__main__": app = wx.PySimpleApp() frame = MyForm().Show() #import wx.lib.inspection #wx.lib.inspection.InspectionTool().Show() app.MainLoop() -- http://mail.python.org/mailman/listinfo/python-list
Re: file/folder naming
On Feb 18, 11:59 pm, Chris Rebert wrote: > On Fri, Feb 18, 2011 at 8:29 PM, ecu_jon wrote: > > im trying to use wxpython to get a source file/files, then a > > destination folder to write them to. the file and folder picker works. > > the problem is, actually copying (actually shutil.copy2() ). i get an > > except error > > Please include the exact text of the error message and accompanying > Traceback. And always do so in the future. > > Cheers, > Chris as i was using tr/except, there is no traceback, or i would have done so. the except error comes back and says it cant copy to the folder. -- http://mail.python.org/mailman/listinfo/python-list
Re: file/folder naming
ok changed the try/except to just a file copy and got this: sourcepath is : [u'I:\\college\\spring11\\capstone-project\ \facbac-009.py'] destpath is : V:\week3 destpath is : V:\week3\facbac-009.py Traceback (most recent call last): File "I:\college\spring11\capstone-project\folder.py", line 53, in button1Click backupfiles() File "I:\college\spring11\capstone-project\folder.py", line 19, in backupfiles shutil.copy2(sourcepath, os.path.join(destpath,os.path.basename(files))) File "C:\Python27\lib\shutil.py", line 127, in copy2 copyfile(src, dst) File "C:\Python27\lib\shutil.py", line 67, in copyfile if _samefile(src, dst): File "C:\Python27\lib\shutil.py", line 62, in _samefile return (os.path.normcase(os.path.abspath(src)) == File "C:\Python27\lib\ntpath.py", line 471, in abspath path = _getfullpathname(path) TypeError: coercing to Unicode: need string or buffer, list found yes i see the list. but shouldnt this "for files in sourcepath:" parse thru the list ... ? -- http://mail.python.org/mailman/listinfo/python-list
Re: file/folder naming
On Feb 19, 1:38 am, Steven D'Aprano wrote: > On Fri, 18 Feb 2011 22:13:42 -0800, ecu_jon wrote: > > ok changed the try/except to just a file copy and got this: > > sourcepath is : > > [u'I:\\college\\spring11\\capstone-project\\facbac-009.py'] > > Note that it's a list. > > > shutil.copy2(sourcepath, > > os.path.join(destpath,os.path.basename(files))) > > Note that you are calling copy2 with the first argument as a list. > > > TypeError: coercing to Unicode: need string or buffer, list found > > Note that the error tells you exactly what is wrong. > > > yes i see the list. > > but shouldnt this "for files in sourcepath:" parse thru the list ... ? > > Yes it does. So what? You don't use files, you use sourcepath each time. > > >>> source = ['a', 'bb', 'ccc'] > >>> for x in source: > > ... print(len(source)) > ... > 3 > 3 > 3 > > -- > Steven so i changed it to shutil.copy2(files, os.path.join(destpath,os.path.basename(files))) seems to be working. in the mornig when im not bleary eyed. ill check again but this look like the fix. thanks. -- http://mail.python.org/mailman/listinfo/python-list