Learnpythonthehardway练习17不工作

时间:2013-11-28 18:55:13

标签: python

我正在练习练习17,似乎无法让它运行。

我像python test.py raw.txt copied.txt一样运行它但收到此错误:

Copying from raw.txt to copied.txt
Traceback (most recent call last):
  File "test.py", line 9, in <module>
    in_file = open(from_file)
IOError: [Errno 2] No such file or directory: 'raw.txt'

我的代码:     来自sys import argv     来自os.path导入

script, from_file, to_file = argv

print "Copying from %s to %s" % (from_file, to_file)

# we could do these two on one line too, how?
in_file = open(from_file)
indata = in_file.read()

print "The input file is %d bytes long" % len(indata)

print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()

out_file = open(to_file, 'w')
out_file.write(indata)

print "Alright, all done."

out_file.close()
in_file.close()

1 个答案:

答案 0 :(得分:0)

试试这个: 现在正在工作目录中搜索所有文件

from sys import argv
from os import getcwd
from os.path import exists, join

cwd = getcwd()
script, from_file, to_file = argv

print "Copying from %s to %s" % (from_file, to_file)

# we could do these two on one line too, how?
in_file = open(join(cwd, from_file))
indata = in_file.read()

print "The input file is %d bytes long" % len(indata)

print "Does the output file exist? %r" % exists(join(cwd, to_file))
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()

out_file = open(join(cwd, to_file), 'w')
out_file.write(indata)

print "Alright, all done."

out_file.close()
in_file.close()