简体   繁体   English

带有用户输入的 Python 3.6 新行

[英]Python 3.6 new line with user input

Made a program that allows the user to enter some text and have a text file be created with that text inside it.制作了一个程序,允许用户输入一些文本并创建一个包含该文本的文本文件。 However, when the user puts \\n it doesn't start a new line.但是,当用户输入 \\n 时,它不会开始新行。 Finding it very difficult to use my program to create text files as it writes all the text on one line lol发现使用我的程序创建文本文件非常困难,因为它将所有文本写在一行上,哈哈

Thanks谢谢

EDIT - Sorry.编辑 - 对不起。 Here is my code (Just the part we are concerned with).这是我的代码(只是我们关心的部分)。

class ReadWriteEdit:
    def Read(File):
        ReadFile = open(File,"r").read()
        print(ReadFile)
    def Write(File, Text):
        WriteFile = open(File,"w")
        WriteFile.write(Text)
    def Edit(File, Text):
        EditFile = open(File,"a")
        EditFile.write(Text)

def Write():
    print("WRITE")
    print("Enter a file location / name")
    FileInput = input("-:")
    print("Enter some text")
    TextInput = input("-:")
    ReadWriteEdit.Write(FileInput, TextInput)

As you have found, special escaped characters are not interpolated in strings read from input, because normally we want to preserve characters, not give them special meanings.如您所见,特殊转义字符不会插入从输入读取的字符串中,因为通常我们希望保留字符,而不是赋予它们特殊含义。

You need to do some adjustment after the input, for example:输入后需要做一些调整,例如:

>>> s=input()
hello\nworld
>>> s
'hello\\nworld'
>>> s = s.replace('\\n', '\n')
>>> s
'hello\nworld'
>>> print(s)
hello
world

You can just add your input to the variable.您可以将您的输入添加到变量中。 You didn't provide any code so I'll just have to improvise:你没有提供任何代码,所以我只需要即兴发挥:

data = open('output.txt', 'w')
a = input('>>')
data.write(a + '\n')
data.close()

But the better solution would be, like the comment below me mentioned, to use sys.stdin.readline()但更好的解决方案是,就像我下面提到的评论一样,使用sys.stdin.readline()

import sys
data.write(sys.stdin.readline())

The easiest (dirtiest?) way IMHO is to print the message and then use input() without a prompt (or with the last part of it)恕我直言,最简单(最脏?)的方法是打印消息,然后在没有提示的情况下使用 input()(或使用它的最后一部分)

print("Are we REALLY sure?\n")
answer = input("[Y/n]")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM