0

I want to write a number of values to a single line in a file. The problem I have is when I write the final index of array a (a[13]), it then prints the following values on a new line. I need to suppress this new line and print all on one line.

I have looked at both:

How to print without newline or space?

Suppress print newline in python 3 str.format

These speak about print statements, I have tried adding ,end='' to the end of my write however it makes no difference.

flow_stats_cleaned.write("{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}"
                            .format(a[2], a[3], a[4], a[5], a[6], a[7], a[8], c[10], c[11],
                             pckts_per_sec, bytes_per_sec, bytes_per_pkt, c[12], a[13], 0),end='', flush=True)


flow_stats_cleaned.write("{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}"
                            .format(a[2], a[3], a[4], a[5], a[6], a[7], a[8], c[10], c[11],
                             pckts_per_sec, bytes_per_sec, bytes_per_pkt, c[12], a[13], 0),end='')

The only thing that works is putting the 0 before the a[13] however I need to preserve order and put the 0 at the end.

These either give an error:

"TypeError: write() takes no keyword arguments"

or write:

"50095,80,-1,-1,2048,6,-1,0,0,1391,164228,118.0647016534867,0,459000000

,0"

or if I put the 0 before the a[13] it gives:

"50095,80,-1,-1,2048,6,-1,0,0,1391,164228,118.0647016534867,0,0,459000000"

But like I said, I need to preserve the original order.

I need the final 0 to not go to a new line. Why would a[13] carry a newline after it?

Community
  • 1
  • 1
HCF3301
  • 508
  • 1
  • 4
  • 14
  • 2
    A file object's `write` method doesn't automatically add any characters. If you're getting a newline in the output, it means you have one in the input. – TigerhawkT3 Feb 06 '19 at 11:30
  • This could be the reason then, the array is generated using: flow_stats.write("{},{},{},{},{}\n". Would that new line attach to the final value? – HCF3301 Feb 06 '19 at 11:32
  • @user5173426 - You're performing the `str.strip` twice there. There are a few ways to eliminate that redundancy, like nesting a generator (`content = [s for s in (word.strip() for word in content) if s]`), or using `map`, `filter`, and `list` (`content = list(filter(None, map(str.strip, content)))`). – TigerhawkT3 Feb 06 '19 at 11:37

0 Answers0