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..
5 Antworten
+ 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')
+ 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")
+ 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...
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,
0
thank you,