【发布时间】:2011-11-06 04:34:45
【问题描述】:
我正在学习 Python the Hard Way,并尝试理解它,而不是一锤定音。我被困在练习 16 上,正如这里已经讨论过的那样:
Very basic Python question (strings, formats and escapes)
但我仍在试图弄清楚为什么这种方法不起作用:
from sys import argv
script, filename = argv
print "Attempting to open the file now."
print open(filename).read()
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file. Goodbye!"
target.truncate()
print "Now I'm going to ask you for three lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
linebreak = "\n"
target.write("%s %s %s %s %s %s") % (line1, linebreak, line2, linebreak, line3, linebreak)
target.write("the ending line")
print "And finally, we close it."
target.close()
我已经为换行建立了一个值,并在 target.write 命令中使用 %s 调用 line1、line2 和 linebreak 值。读取时不应该解析为“line1 \n line2 \n line3 \n”吗?
这可能相当于被一个孩子问是什么让天空保持向上或什么的,我为有点厚实道歉。谢谢!
【问题讨论】:
-
你能详细说明“不起作用”吗?你有例外吗?如果有,请提供。如果不是,请说明您的预期和实际收到的内容。
-
如果有机会我可以猜到 - 当您重新打开文件以验证其内容时,您使用的编辑器是否可能无法将
\n识别为换行,它实际上是在寻找\r\n(回车+换行)?例如,这在 Windows 上的记事本中很常见。 -
道歉——当它到达脚本的 target.write 部分时,我收到“TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'”。
标签: python string line new-operator