繁体   English   中英

我不明白为什么在Python 2.x中无法正确打开()文件

[英]I don't understand why can't open() file correctly in Python 2.x

这是我的代码:

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: ")

它运作良好。

我想用更少的代码定义一个函数,但是我遇到了一个问题。

我将修改处理功能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 ,我们需要进行一些修改。 让我知道是否是这种情况...

您在confirmfile_name所做的更改不会影响您传递给该函数的参数。 您应该在confirm返回file_name的最终值,并使调用者将其分配给适当的变量。

删除第11行(确认(to_file)),新文件不能存在

我认为您可以使用此:

with open('file.txt', 'r') as f:
    with open('newfile.txt', 'w') as nf:
        nf.write(f.read())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM