2014-10-08 3 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()) 

, 나는 (맥에)이 입력 :

/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

+0

정확히 무엇을 의미합니까? 나는이 모든 것을 아직도 배우고있다. – Shayd3

+0

@ o11c 그것은 사용자가 궁금해하는 것이면 코드의 다음 섹션으로 계속 진행하려면 enter 키를 누르라는 프롬프트를 표시하기 때문입니다. – Shayd3

답변

1

백 슬래시는 파일 이름의 일부가 아닙니다. 오히려 다른 의미를 지닌 문자 (이 경우 쉘)를 이스케이프 처리하기 위해서만 존재합니다. raw_input은 이스케이프가 필요하지 않습니다.

/Users/Ross/Desktop/School/Intro To Python/lab5/readcopy.txt을 입력하거나 상대 경로를 사용하는 것이 좋습니다.