Reputation: 83
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.
Upvotes: 0
Views: 376
Reputation: 53663
I would modify the function to handle the raw_input
internally, you can do something like this which will loop while
the input is not an existing file, and will return the file's path if it is an existing file.
from os.path import exists
def getFileName(msg):
file_name = raw_input(msg)
while not exists(file_name):
print "File {} doesn't exist. Try again!".format(file_name)
file_name = raw_input(msg)
return file_name
from_file = getFileName("copy from: ")
to_file = getFileName("copy to: ")
with open(to_file, 'w') as f:
f.write(open(from_file).read())
NOTE This assumes both files already exist. If your intent is to create the to_file
at run-time, we need to make some modification. Let me know if that is the case...
Upvotes: 3
Reputation: 555
Remove line 11 (confirm(to_file)), the new file cant exists
i think that you could use this:
with open('file.txt', 'r') as f:
with open('newfile.txt', 'w') as nf:
nf.write(f.read())
Upvotes: 1
Reputation: 49920
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.
Upvotes: 2