Python - 打开文本文件并通过raw_input追加行

时间:2014-10-08 03:40:25

标签: python append 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 '

关于我如何做到这一点的任何输入?想要使用用户输入添加新行的代码是否正确?

感谢。

1 个答案:

答案 0 :(得分:1)

反斜杠不是文件名的一部分。相反,它们的存在只是为了转义其他有意义的字符,在本例中是shell。 raw_input不需要任何转义。

只需输入/Users/Ross/Desktop/School/Intro To Python/lab5/readcopy.txt,或者更好地使用相对路径。