0

I am trying to write a new line to a file after writing a variable. How do I do that? Here's what I have but isn't working:

abc = "Test"
myfile.write(abc\n)
1
  • It's a string abc="Test\n" Commented Oct 3, 2020 at 22:27

3 Answers 3

3

Try this:

abc = "Test"
myfile.write(f"{abc}\n")
Sign up to request clarification or add additional context in comments.

Comments

0

You can to concatenate both strings, the one stored in the variable abc and "\n"

myfile.write(abc + "\n")

3 Comments

You can't concatenate two strings together when writing a file.
@RyanPublications Can you explicit that ? Because 2 strings concatenated is just one string, then it's written in the file ;)
@RyanPublications not possible, that does 100% same as the accepted answer ;)
0

You may want to consider where the cursor is in your file_handle.

file_handle.write() will write from the beginning of the file if you've open(file, 'w') whereas file_handle.write() will add to the end (And is probably what you want) if you open(file, 'a'). Other than that, the \n in the other answers are also what you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.