Home > Software design >  Formating user input into a txt file
Formating user input into a txt file

Time:11-06

I am trying to format these 2 user inputs into a file on seperate lines I know I have to us the \n to use a new line but I keep getting errors with where I put it, is there another way to get each user input on a new line?

'''

def userfile():
   text = []

   text.append(input("Enter sentence 1: "))
   text.append(input("Enter sentence 2: "))

   file = open(os.path.join(sys.path[0], "sample2.txt"), "w")
   file.writelines(text)
   file.close()

   newfile = open(os.path.join(sys.path[0],"sample2.txt"), "r")
   print(newfile.read())

def main():
   #txtfile()
   userfile()

if __name__ == "__main__":
    main()

CodePudding user response:

You have to append it at the end of user input:

text.append(input("Enter sentence 1: ")   "\n")
text.append(input("Enter sentence 2: ")   "\n")

CodePudding user response:

There are several ways of doing this.

Explictly Looping

def userfile():
    text = []

    text.append(input("Enter sentence 1: "))
    text.append(input("Enter sentence 2: "))

    with open(os.path.join(sys.path[0], "sample2.txt"), "w") as file:
        for line in text:
            print(line, file=file)
    ... # etc.

Creating a Single String

def userfile():
    text = []

    text.append(input("Enter sentence 1: "))
    text.append(input("Enter sentence 2: "))

    with open(os.path.join(sys.path[0], "sample2.txt"), "w") as file:
        print('\n'.join(text), file=File)
    ... # etc.

Appending a Newline to the Input

def userfile():
    text = []

    text.append(input("Enter sentence 1: ")   '\n')
    text.append(input("Enter sentence 2: ")   '\n')

    with open(os.path.join(sys.path[0], "sample2.txt"), "w") as file:
        file.writelines(text)
    ... # etc.
  • Related