1

I am using the following commands inside a Loop to open a .txt file and write some results on the file.

with open ('results.txt', 'a') as file: 
    file.write('%s %d %s %s \n' %(timestamp, v, str(dcur), str(gcur)))

However, the results are not printed on the same line at the .txt file and str(gcur) appears on the next one.

Why does this happen and how could it be solved?

3
  • 1
    try with (timestamp, v, str(dcur).rstrip("\n"), str(gcur).rstrip("\n"))) Commented Oct 24, 2019 at 9:55
  • 1
    @AthinaPap It is because of \n in your file.write Commented Oct 24, 2019 at 9:57
  • 1
    If you have no \n in your strings gcur and dcur, then it should not happen. Could you give a complete example with inputs and outputs? Thanks Commented Oct 24, 2019 at 9:59

2 Answers 2

3

Most probably is because when calling str to dcur it adds a "\n" somehow.

You can stript it:

with open ('results.txt', 'a') as file: 
    file.write('%s %d %s %s \n'.format(timestamp, v, str(dcur).rstript("\n"), str(gcur).rstript("\n")))
Sign up to request clarification or add additional context in comments.

Comments

0

You are printing the format string '%s %d %s %s \n' in which %s and %d are replaced by timestamp, v, str(dcur), str(gcur) variables. Note the \n in the end of your format string — this is newline character. You should remove it if you want everything to be printed on the same line, like this:

with open ('results.txt', 'a') as file: 
    file.write('%s %d %s %s' %(timestamp, v, str(dcur), str(gcur)))

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.