这是我的代码:
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())
终端输出
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'
为什么打开错误的文件?
如何解决?
当我这样做时:
from_file = raw_input("copy from: ")
while not exists(from_file):
print "File doesn't exist."
from_file = raw_input("File name: ")
效果很好。
我想为更少的代码定义一个函数,但是我遇到了问题。
答案 0 :(得分:3)
我会在内部修改函数来处理raw_input
,你可以做类似这样的事情,它将循环while
输入不是现有文件,并且如果它是 现有文件。
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())
注意这假设两个文件都已存在。如果您的目的是在运行时创建 to_file
,我们需要进行一些修改。如果是这样的话,请告诉我......
答案 1 :(得分:2)
您在file_name
内对confirm
所做的更改不会影响您传递给该功能的参数。您应该在file_name
中返回confirm
的最终值,并让调用者将其分配给相应的变量。
答案 2 :(得分:1)
删除第11行(确认(to_file)),新文件无法存在
我认为你可以使用它:
with open('file.txt', 'r') as f:
with open('newfile.txt', 'w') as nf:
nf.write(f.read())