简体   繁体   中英

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. 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()

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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