如果我有这段代码来编写txt文件,我只是想知道为什么每次我在输入中键入\ n时都不会创建这样的换行符。
<a href="/buttons/" class="link external panel-close">Buttons</a>
这是代码
This is the example txt file\n it doesn't create a new line\n how can I make it do it?
答案 0 :(得分:1)
您可以使用replace:
def create():
path = input("What file would you like to create: ")
output_file = open(path, 'x')
text = input("What would you like to write? ")
output_file.write(text.replace('\\n', '\n'))
output_file.close()
def append():
path = input("What file would you like to append: ")
output_file = open(path, 'a')
text = input("What would you like to write?")
output_file.writelines(text.replace('\\n', '\n'))
output_file.close()
write = input("Would you like to write something today, or edit? ")
if write == "Write":
create()
if write == "Edit":
append()
答案 1 :(得分:1)
这是一个非常简单的答案。
input = input("Would you like to Write a new document, or Edit an existing one? ")
if input == Write:
file = open(path, "w")
file.write(text)
file.write("\r\n")
file.close()
if input == Edit:
file = open(path, "a")
file.write(text)
file.write("\r\n")
file.close()
答案 2 :(得分:1)
How do you input escape sequences in Python?中提到了\n
与input
不兼容的原因。 input
函数无法识别任何转义序列,例如\n
,因为它会按字面意义解释文本。
要将\n
解释为来自text
的换行符,请进行以下导入并调整write()
和writelines()
的参数,以允许用户输入{{1} }包括新行:
This is the example txt file\n it doesn't create a new line\n how can I make it do it?