How to use /n in Python3?

Viewed 1467

In order to get the output line by line and not after each other, I want to start using /n command.

Here is the piece of code where I think it should be placed:

password_for = input('This password is for: ')
your_pass =  'Your password for {} is: {}'.format(password_for, password)

save_path = '/Users/"MyUsername"/Desktop'
name_of_file = input("What is the name of the file: ")
completeName = os.path.join(save_path, name_of_file+".txt")
with open(completeName, "a+") as file1:
    file1.write(your_pass)

The /n command should be used to get the text that's supposed to be written (output), line by line like this:

Input 1
input 2

But now the output is working like this:

Input1Input2

Maybe /N isn't the solution? Let me know!

4 Answers

Some characters must be "escaped" in order to enter them into a string. In this case, you want a newline character which is written \n in Python.

Anyway, to answer your question:

with open(completeName, "a+") as file1:
    file1.write(your_pass + '\n')

This will concatenate the string in your_pass with the string containing one newline character and then call file1.write.

password_for = input('This password is for: ')
your_pass =  'Your password for {} is: {}'.format(password_for, password)

save_path = '/Users/"MyUsername"/Desktop'
name_of_file = input("What is the name of the file: ")
completeName = os.path.join(save_path, name_of_file+".txt")
with open(completeName, "a+") as file1:
    file1.write(your_pass + '\n')  # You need to place '\n' here.

You can use it with string concatenation operator i.e. "+ operator" like given below:

file1.write(your_pass + '\n')

You just need to add this to your code:-

+ '\n'

In the last line:-

file1.write(your_pass + '\n')
Related