I don't understand why can't open() file correctly in Python 2.x
Question: Here is my code:

    
    
    from os.path import exists
    
    def confirm(file_name):
        while not exists(file_name):
            print "File doesn't exist."
            file_name = raw_input("File name: ")
    
    from_file = raw_input("copy from: ")
    confirm(from_file)
    to_file = raw_input("copy to: ")
    confirm(to_file)
    
    with open(to_file, 'w')as f:
        f.write(open(from_file).read())
    

Output in Terminal

    
    
    copy from: asd.txt
    File doesn't exist.
    File name: test.txt
    copy to: dsa.txt
    File doesn't exist.
    File name: test.py
    Traceback (most recent call last):
      File "ex17.py", line 17, in <module>
        f.write(open(from_file).read())
    IOError: [Errno 2] No such file or directory: 'ad.txt'
    

Why does it open the incorrect file?

How to fix it?

And when I do this:

    
    
       from_file = raw_input("copy from: ")
       while not exists(from_file):
           print "File doesn't exist."
           from_file = raw_input("File name: ")
    

It Works well.

I want to define a function for less code, but I get a problem.


Answer: The changes to `file_name` you make inside of `confirm` do not affect the
parameter you passed to that function. You should return the final value of
`file_name` in `confirm`, and have the caller assign that to the appropriate
variable.

