为什么 Python 的 .write 会导致文本行周围出现单引号?

Why does Python's .write cause single quotes around the lines of text?

出于某种原因,下面的代码将每个 'line' 文本写入我的 .txt 文件,每行都用单引号引起来。有没有办法避免这种情况发生?还是我做了什么导致了这个问题?

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."

target.write("%r\n%r\n%r\n" % (line1, line2, line3))

print "And finally, we close it."
target.close()

您在格式字符串中使用 %r,它会打印行的 repr()。你要的是%s:

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."

target.write("%s\n%s\n%s\n" % (line1, line2, line3))

print "And finally, we close it."
target.close()

此外,我建议使用 with 语句来确保 target 文件已关闭,而不是手动调用 close()。这将确保文件关闭,即使您的代码导致异常:

with open(filename) as target:
    ... do your manipulation ...
    # target is automatically closed at the end of the with block.
    # No need to call target.close() manually.

您可能应该使用 %s 而不是 %r。后一个选项用于 repr()(即,您可以使用输出生成 Python 字符串对象)。