0

I am trying to append new information in a for loop to a new line and then write it to a text file. A simple sample code is giving me issues:

ID = "A1"
val = 0.4

tmp = []

for i in range(0,10):
    aa = (ID + ',' + repr(val))
    tmp.append(aa)

text_file = open("output.txt", "w")
text_file.write("%s\n" % tmp)

However, the contents of 'output.txt' is:

['A1,0.4', 'A1,0.4', 'A1,0.4', 'A1,0.4', 'A1,0.4', 'A1,0.4', 'A1,0.4', 'A1,0.4', 'A1,0.4', 'A1,0.4']

Whereas I would want each iteration within the loop on a newline:

['A1,0.4'
'A1,0.4'
...
...
'A1,0.4']

I know adding a newline '\n' should work, but it is simply adding this as text and not working as a newline. Some of these files are 1000's of lines long, so would opening the text file and writing the output each time be very time consuming as opposed to creating one, large array and output that to the text file in the end?

2 Answers 2

3

It would be much simpler using join, like this

ID = "A1"
val = 0.4

tmp = []

for i in range(0,10):
    aa = (ID + ',' + repr(val))
    tmp.append(aa)

data = '[{}]'.format('\n'.join(tmp))
text_file = open("output.txt", "w")
text_file.write(data)
Sign up to request clarification or add additional context in comments.

1 Comment

It prints a list to the file, maybe this is not wanted.
2
ID = "A1"
val = 0.4

tmp = []

for i in range(0, 10):
    aa = (ID + ',' + repr(val) + "\n")
    tmp.append(aa)

text_file = open("output.txt", "w")

for i in range(0, 10):
    text_file.write("{}".format(tmp[i]))

This code produces the following output:

A1,0.4
A1,0.4
...
A1,0.4

Is this what you had in mind?

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.