[Tutor] Copy files

Alan Gauld alan.gauld at freenet.co.uk
Tue Jan 31 01:45:42 CET 2006


David,

Can I suggest you rethink your variable names?
That might make it clearer what is happening.

>  def compare_files(file_name1, file_name2):
>      x = cmp (file_name1, file_name2)
>      return x

Seems fair enough except file_name1 and file_name2 are actually file 
*contents*!
And in fact the function really just compares 2 strings. in fact it compares 
2 anythings,
It just returns the resulkt of cmp() so you could lose it entirely!

You might find it easier to use the filecmp.cmp() function which compares
two files using their filenames as arguments.

>  def open_files(file_name):
>      file_is = open(file_name,'r')
>      file_conts = file_is.read()
>      return file_conts

And "open_files" actually only opens one file and then returns it contents.
So a name like "contents_of(filename)" would be more descriptive

>  def change_files(file_1, file_2):
>      yesorno = raw_input("Do you want them to be the same Y or N ")
>      yesorno = string.upper(yesorno)
>      if yesorno == 'Y':
>          try:
>              shutil.copy2(file_1, file_2)
>              print "copy has been done "
>          except:
>              print "it did not work"

The user prompt doesn't give the user much clue what he is agreeing to
make the same but otherwise this seems OK. I assume you have write
access to both files?

>  #main
>  file_name1 = open_files("test1.txt")
>  file_name2 = open_files("test2.txt")
>  file_name3 = open_files("test3.txt")

the 3 variables above each contain not the *name* of the file but the 
contents.

>  import shutil
>  import string
>
>  x = compare_files(file_name3, file_name1)

x = cmp(f1,f2)

would be just as useful.

>  if x != 0:
>      print  "test1 and test3 are different"
>      change_files("test1.txt", "text3.txt", file_name1)

The function above has 2 parameters but you are passing 3 arguments.
I'd expect Python to complain at that? Also the first two are filenames
but the last is the contents of file1

>  else:
>      file_name1 = "test2.txt"

but here you overwrite the contents with the filename

>      print file_name1

and print "text2.txt"
I'm not sure what thats trying to do?

>      x = compare_files(file_name3, file_name2)

again a simple cmp() would do the same job

>      if x != 0:
>          print "test2 and test3 are different"
>          change_files("test2.txt", "text3.txt")

Since you didn't mention an error I assume your program always
goes down this path?

Despite the confusing names it looks like the program must be
going down the second branch and trying to copy the two files.
The only obvious thing I can think of is that the files do not have
write permissions set appropriately?

Not sure if that helps at all but the best I can do at 12:45am...:-)

Alan G. 



More information about the Tutor mailing list