2013-11-28 42 views
0

我正在練習17,似乎無法讓它運行。Learnpythonthehardway練習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進口的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() 
+2

請追溯是文字,您可以在這裏複製並粘貼。 –

+3

在'python'目錄中是'raw.txt'嗎? –

回答

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() 
+0

'PS C:\ Users \ Schneeder> cd python PS C:\ Users \ Schneeder \ python> python test.py raw.txt copied.txt 從raw.txt複製到copied.txt Traceback(最近一次調用last ): 文件「test.py」,第11行,在 in_file = open(join(cwd,from_file)) IOError:[Errno 2]沒有這樣的文件或目錄:'C:\\ Users \\ Schneeder \ \ python \\ raw.txt' PS C:\ Users \ Schneeder \ python>' – user3047058

+0

@ user3047058你真的在那個目錄下有那個文件嗎?請檢查。 – akaRem