Python打开文本文件并通过raw_inpu附加行

2024-04-25 09:15:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图添加到这段代码中,这样我就可以通过用户输入将行附加到文本文件中。到目前为止,我得到的是:

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上):

^{pr2}$

它返回给我的是:

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 '

有什么关于我该怎么做的吗?另外,代码是否正确,希望在用户输入中添加新行?在

谢谢。在


Tags: thetoinfromyouinputrawopen
1条回答
网友
1楼 · 发布于 2024-04-25 09:15:36

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

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

相关问题 更多 >