2014-10-08 81 views
0

我試圖添加到此代碼中,以便可以通過用戶輸入將行添加到文本文件。這是我到目前爲止有:Python - 打開文本文件並通過raw_input添加行

from sys import argv 
from os.path import exists 

print "Let's read and write to a file now!" 

raw_input ("Press enter when ready to proceed...") 

script, from_file, to_file = argv 

print "Let's copy one file and put it into another file!" 
print "I'm going to copy from %s to %s!" % (from_file, to_file) 

in_file = open(from_file) 
indata = in_file.read() 

print "The input file you picked is %d bytes long, cool huh?" % len(indata) 
print "Does the output file you are trying to make exist? %r" % exists(to_file) 

print "Ready, hit RETURN to continue, CTRL-C or Command+C to abort." 
raw_input("Press enter when ready to proceed...") 
print "Are you SURE that you want to continue?... This could blow the world up. CTRL-C or Command+C to abort." 
raw_input("Press enter when ready to proceed...") 
print "Last chance... Do you really want to risk doing off with the human race?... CTRL-C or Command+C to abort." 
raw_input("Press enter when ready to proceed...") 

print "Alright! I'm doing it!" 

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

print "Oh... We are still alive. Well, have fun with your new file!" 


out_file.close() 
in_file.close() 

print "Let's try and append a line to the new copied file!" 
raw_input("Press enter when ready to proceed...") 

print "Type in the file path for the file you want to edit!: " 
filename = raw_input(">") 

with open(filename, "a") as myfile: 
    myfile.write(raw_input()) 

當問我要的文件路徑,我輸入這個(在Mac):

/Users/Ross/Desktop/School/Intro\ To\ Python/lab5/readcopy.txt 

它返回我這個:

Traceback (most recent call last): 
    File "/Users/Ross/Desktop/School/Intro To Python/lab5/readcopy.py", line 43, in <module> 
    with open(filename, "a") as myfile: 
IOError: [Errno 2] No such file or directory: '/Users/Ross/Desktop/School/Intro\\ To\\  Python/lab5/readcopy.txt ' 

有關我如何做到這一點的任何輸入?另外,代碼是否需要用戶輸入添加新行?

謝謝。

+0

你爲什麼不在任何地方分配'raw_input()'的結果? – o11c 2014-10-08 03:48:06

+0

你是什麼意思?我仍然在學習這一切。 – Shayd3 2014-10-08 03:53:37

+0

@ o11c因爲它提示用戶按Enter鍵以繼續下一段代碼,如果這是你想知道的。 – Shayd3 2014-10-08 03:54:47

回答

1

反斜槓不是文件名的一部分。相反,它們的存在僅僅是爲了逃避那些有意義的字符,在這種情況下是爲了逃避shell。 raw_input不需要任何轉義。

只需輸入/Users/Ross/Desktop/School/Intro To Python/lab5/readcopy.txt,或更好地使用相對路徑。

相關問題