Nima Alidoust
Nima Alidoust

Reputation: 55

How can I append to the new line of a file while using write()?

In Python: Let's say I have a loop, during each cycle of which I produce a list with the following format: ['n1','n2','n3'] After each cycle I would like to write to append the produced entry to a file (which contains all the outputs from the previous cycles). How can I do that?

Also, is there a way to make a list whose entries are the outputs of this cycle? i.e. [[],[],[]] where each internal []=['n1','n2','n3] etc

Upvotes: 1

Views: 2971

Answers (3)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29093

Hope this can help you:

lVals = []
with open(filename, 'a') as f:
    for x,y,z in zip(range(10), range(5, 15), range(10, 20)):
        lVals.append([x,y,z])
        f.write(str(lVals[-1]))

Upvotes: 0

ylsun
ylsun

Reputation: 31

f=open(file,'a') first para is the path of file,second is the pattern,'a' is append,'w' is write, 'r' is read ,and so on im my opinion,you can use f.write(list+'\n') to write a line in a loop ,otherwise you can use f.writelines(list),it also functions.

Upvotes: 2

Tadeck
Tadeck

Reputation: 137300

Writing single list as a line to file

Surely you can write it into a file like, after converting it to string:

with open('some_file.dat', 'w') as f:
    for x in xrange(10):  # assume 10 cycles
        line = []
        # ... (here is your code, appending data to line) ...
        f.write('%r\n' % line)  # here you write representation to separate line

Writing all lines at once

When it comes to the second part of your question:

Also, is there a way to make a list whose entries are the outputs of this cycle? i.e. [[],[],[]] where each internal []=['n1','n2','n3'] etc

it is also pretty basic. Assuming you want to save it all at once, just write:

lines = []  # container for a list of lines
for x in xrange(10):  # assume 10 cycles
    line = []
    # ... (here is your code, appending data to line) ...
    lines.append('%r\n' % line)  # here you add line to the list of lines
# here "lines" is your list of cycle results
with open('some_file.dat', 'w') as f:
    f.writelines(lines)

Better way of writing a list to file

Depending on what you need, you should probably use one of the more specialized formats, than just a text file. Instead of writing list representations (which are okay, but not ideal), you could use eg. csv module (similar to Excel's spreadsheet): http://docs.python.org/3.3/library/csv.html

Upvotes: 4

Related Questions