When writing a file in python, how do we use a new line command when inputting text into the file using file.write()??? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

When writing a file in python, how do we use a new line command when inputting text into the file using file.write()???

can't seem to wrap my head around it yet. still learning..

22nd Dec 2016, 5:44 AM
Deon MacArthur
Deon MacArthur - avatar
5 Answers
+ 2
Do you means "when OUTputting text into the file"? ( INput, the program get a value, from user or whatever like a file, so it's an importation, while OUTput is a value exportation ) Add the '\n' ( new line ) character after each of your lines, like this: file.write(my_string+'\n') Of course, you can append this char alone also: file.write(my_string) file.write('\n')
22nd Dec 2016, 6:47 AM
visph
visph - avatar
+ 2
So I've already give the solution... Put '\n' at the end of your input question like that: try: file=open(input("enter file name/location:\n"),"w") file.write(input("enter text here:\n")) finally: file.close() file=open(input("enter file name:\n"),"r") cont=file.read() print(cont) file.close() print("end test.") Normally, just after the user input, the new line is automatic... If with python 3 you have a different behaviour, you can add this after each call to input: print("\n")
22nd Dec 2016, 11:51 AM
visph
visph - avatar
+ 1
Need precisions for understanding yours goals... Could you post your code? Or at least describe more what your code will do? ( I don't understand the link between file writing followed by an user input and the use of a "new line command" ^^ ) Else, when you use the input function like this: user_input = input("question?") The text cursor is on the next char position next the last of the question string. So, if you want the cursor ( and the user entry ) on a new line, you need to add the character "control" ( not "command" ;) ) corresponding ( '\n' ): user_input = input("question?\n") Another note: In Python 2.7 and 3.x the behaviour of the input function differs. With 2.7, all user entries are interpreted, so if you set a string, there's a great probability to obtain an error ( name 'text' not defined ) or at least not the expected result :( In this case, you'll need tu use raw_input function instead of input...
22nd Dec 2016, 10:31 AM
visph
visph - avatar
0
try: file=open(input("enter file name/location: "),"w") file.write(input("enter text here: ")) finally: file.close() file=open(input("enter file name: "),"r") cont=file.read() print(cont) file.close() print("end test.") This is the code, used in python3x. My question is how can I start a new line when I use the input func,
22nd Dec 2016, 11:19 AM
Deon MacArthur
Deon MacArthur - avatar
0
thank you,
22nd Dec 2016, 12:24 PM
Deon MacArthur
Deon MacArthur - avatar