Writing a list to a file with Python, with newlines
Asked Answered
P

26

973

How do I write a list to a file? writelines() doesn't insert newline characters, so I need to do:

f.writelines([f"{line}\n" for line in lines])
Pratfall answered 22/5, 2009 at 17:52 Comment(2)
do note that writelines doesn't add newlines because it mirrors readlines, which also doesn't remove them.Flanagan
its between json vs pickle. read all about it - #27746000Transcurrent
L
1306

Use a loop:

with open('your_file.txt', 'w') as f:
    for line in lines:
        f.write(f"{line}\n")

For Python <3.6:

with open('your_file.txt', 'w') as f:
    for line in lines:
        f.write("%s\n" % line)

For Python 2, one may also use:

with open('your_file.txt', 'w') as f:
    for line in lines:
        print >> f, line

If you're keen on a single function call, at least remove the square brackets [], so that the strings to be printed get made one at a time (a genexp rather than a listcomp) -- no reason to take up all the memory required to materialize the whole list of strings.

Lefevre answered 22/5, 2009 at 18:4 Comment(0)
F
501

What are you going to do with the file? Does this file exist for humans, or other programs with clear interoperability requirements?

If you are just trying to serialize a list to disk for later use by the same python app, you should be pickleing the list.

import pickle

with open('outfile', 'wb') as fp:
    pickle.dump(itemlist, fp)

To read it back:

with open ('outfile', 'rb') as fp:
    itemlist = pickle.load(fp)
Flanagan answered 22/5, 2009 at 18:10 Comment(2)
"Warning: The pickle module is not secure. Only unpickle data you trust. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling. Never unpickle data that could have come from an untrusted source, or that could have been tampered with." -- From the same manual page linked on the answer.Twospot
Pickle has the problem that it can change whenever you upgrade python. What you pickle in python 3.n you might not be able to unpickle in python 3.(n+1). This bit me once.Addie
T
444

Simpler is:

with open("outfile", "w") as outfile:
    outfile.write("\n".join(itemlist))

To ensure that all items in the item list are strings, use a generator expression:

with open("outfile", "w") as outfile:
    outfile.write("\n".join(str(item) for item in itemlist))

Remember that itemlist takes up memory, so take care about the memory consumption.

Trotyl answered 22/5, 2009 at 17:58 Comment(1)
No trailing newline, uses 2x space compared to the loop.Marentic
F
106

Using Python 3 and Python 2.6+ syntax:

with open(filepath, 'w') as file_handler:
    for item in the_list:
        file_handler.write("{}\n".format(item))

This is platform-independent. It also terminates the final line with a newline character, which is a UNIX best practice.

Starting with Python 3.6, "{}\n".format(item) can be replaced with an f-string: f"{item}\n".

Fipple answered 22/7, 2011 at 14:30 Comment(1)
Possible duplicate of: https://mcmap.net/q/53276/-writing-a-list-to-a-file-with-python-with-newlinesMirza
J
97

Yet another way. Serialize to json using simplejson (included as json in python 2.6):

>>> import simplejson
>>> f = open('output.txt', 'w')
>>> simplejson.dump([1,2,3,4], f)
>>> f.close()

If you examine output.txt:

[1, 2, 3, 4]

This is useful because the syntax is pythonic, it's human readable, and it can be read by other programs in other languages.

Josephus answered 22/5, 2009 at 18:20 Comment(0)
L
44

I thought it would be interesting to explore the benefits of using a genexp, so here's my take.

The example in the question uses square brackets to create a temporary list, and so is equivalent to:

file.writelines( list( "%s\n" % item for item in list ) )

Which needlessly constructs a temporary list of all the lines that will be written out, this may consume significant amounts of memory depending on the size of your list and how verbose the output of str(item) is.

Drop the square brackets (equivalent to removing the wrapping list() call above) will instead pass a temporary generator to file.writelines():

file.writelines( "%s\n" % item for item in list )

This generator will create newline-terminated representation of your item objects on-demand (i.e. as they are written out). This is nice for a couple of reasons:

  • Memory overheads are small, even for very large lists
  • If str(item) is slow there's visible progress in the file as each item is processed

This avoids memory issues, such as:

In [1]: import os

In [2]: f = file(os.devnull, "w")

In [3]: %timeit f.writelines( "%s\n" % item for item in xrange(2**20) )
1 loops, best of 3: 385 ms per loop

In [4]: %timeit f.writelines( ["%s\n" % item for item in xrange(2**20)] )
ERROR: Internal Python error in the inspect module.
Below is the traceback from this internal error.

Traceback (most recent call last):
...
MemoryError

(I triggered this error by limiting Python's max. virtual memory to ~100MB with ulimit -v 102400).

Putting memory usage to one side, this method isn't actually any faster than the original:

In [4]: %timeit f.writelines( "%s\n" % item for item in xrange(2**20) )
1 loops, best of 3: 370 ms per loop

In [5]: %timeit f.writelines( ["%s\n" % item for item in xrange(2**20)] )
1 loops, best of 3: 360 ms per loop

(Python 2.6.2 on Linux)

Lunneta answered 17/2, 2011 at 18:13 Comment(0)
J
31

Because i'm lazy....

import json
a = [1,2,3]
with open('test.txt', 'w') as f:
    f.write(json.dumps(a))

#Now read the file back into a Python list object
with open('test.txt', 'r') as f:
    a = json.loads(f.read())
Jaclin answered 10/8, 2017 at 20:55 Comment(0)
S
25

In Python 3 you can use print and * for argument unpacking:

with open("fout.txt", "w") as fout:
    print(*my_list, sep="\n", file=fout)
Stallworth answered 5/5, 2020 at 15:3 Comment(0)
H
21

Serialize list into text file with comma sepparated value

mylist = dir()
with open('filename.txt','w') as f:
    f.write( ','.join( mylist ) )
Hadwin answered 18/11, 2015 at 8:51 Comment(0)
D
18

Simply:

with open("text.txt", 'w') as file:
    file.write('\n'.join(yourList))
Dung answered 4/1, 2022 at 15:56 Comment(1)
B
17

In General

Following is the syntax for writelines() method

fileObject.writelines( sequence )

Example

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "rw+")
seq = ["This is 6th line\n", "This is 7th line"]

# Write sequence of lines at the end of the file.
line = fo.writelines( seq )

# Close opend file
fo.close()

Reference

http://www.tutorialspoint.com/python/file_writelines.htm

Boating answered 9/5, 2013 at 1:1 Comment(0)
C
14
file.write('\n'.join(list))
Clarhe answered 22/5, 2009 at 18:29 Comment(0)
C
14

Using numpy.savetxt is also an option:

import numpy as np

np.savetxt('list.txt', list, delimiter="\n", fmt="%s")
Candlepower answered 13/8, 2020 at 13:11 Comment(0)
A
9

You can also use the print function if you're on python3 as follows.

f = open("myfile.txt","wb")
print(mylist, file=f)
Afraid answered 30/9, 2015 at 21:50 Comment(0)
R
8
with open ("test.txt","w")as fp:
   for line in list12:
       fp.write(line+"\n")
Rapacious answered 10/9, 2015 at 18:14 Comment(0)
N
5

I recently found Path to be useful. Helps me get around having to with open('file') as f and then writing to the file. Hope this becomes useful to someone :).

from pathlib import Path
import json
a = [[1,2,3],[4,5,6]]
# write
Path("file.json").write_text(json.dumps(a))
# read
json.loads(Path("file.json").read_text())
Nucleonics answered 15/9, 2021 at 18:37 Comment(0)
O
4

Why don't you try

file.write(str(list))
Outburst answered 19/8, 2015 at 23:47 Comment(0)
D
3

You can also go through following:

Example:

my_list=[1,2,3,4,5,"abc","def"]
with open('your_file.txt', 'w') as file:
    for item in my_list:
        file.write("%s\n" % item)

Output:

In your_file.txt items are saved like:

1

2

3

4

5

abc

def

Your script also saves as above.

Otherwise, you can use pickle

import pickle
my_list=[1,2,3,4,5,"abc","def"]
#to write
with open('your_file.txt', 'wb') as file:
    pickle.dump(my_list, file)
#to read
with open ('your_file.txt', 'rb') as file:
    Outlist = pickle.load(file)
print(Outlist)

Output: [1, 2, 3, 4, 5, 'abc', 'def']

It save dump the list same as a list when we load it we able to read.

Also by simplejson possible same as above output

import simplejson as sj
my_list=[1,2,3,4,5,"abc","def"]
#To write
with open('your_file.txt', 'w') as file:
    sj.dump(my_list, file)

#To save
with open('your_file.txt', 'r') as file:
    mlist=sj.load(file)
print(mlist)
Dead answered 2/1, 2021 at 17:41 Comment(0)
O
2

This logic will first convert the items in list to string(str). Sometimes the list contains a tuple like

alist = [(i12,tiger), 
(113,lion)]

This logic will write to file each tuple in a new line. We can later use eval while loading each tuple when reading the file:

outfile = open('outfile.txt', 'w') # open a file in write mode
for item in list_to_persistence:    # iterate over the list items
   outfile.write(str(item) + '\n') # write to the file
outfile.close()   # close the file 
Odor answered 11/7, 2018 at 7:9 Comment(0)
C
1

Another way of iterating and adding newline:

for item in items:
    filewriter.write(f"{item}" + "\n")
Chintzy answered 14/6, 2018 at 20:54 Comment(0)
S
0

In Python3 You Can use this loop

with open('your_file.txt', 'w') as f:
    for item in list:
        f.print("", item)
Soft answered 28/1, 2020 at 9:46 Comment(0)
U
0

Redirecting stdout to a file might also be useful for this purpose:

from contextlib import redirect_stdout
with open('test.txt', 'w') as f:
  with redirect_stdout(f):
     for i in range(mylst.size):
        print(mylst[i])
Uvarovite answered 9/9, 2020 at 7:53 Comment(0)
C
0

i suggest this solution .

with open('your_file.txt', 'w') as f:        
    list(map(lambda item : f.write("%s\n" % item),my_list))   
Cache answered 5/7, 2021 at 22:3 Comment(0)
G
-1

Let avg be the list, then:

In [29]: a = n.array((avg))
In [31]: a.tofile('avgpoints.dat',sep='\n',dtype = '%f')

You can use %e or %s depending on your requirement.

Gingerich answered 26/4, 2011 at 7:16 Comment(0)
G
-1

i think you are looking for an answer like this.

f = open('output.txt','w')
list = [3, 15.2123, 118.3432, 98.2276, 118.0043]
f.write('a= {:>3d}, b= {:>8.4f}, c= {:>8.4f}, d= {:>8.4f}, e= 
{:>8.4f}\n'.format(*list))
f.close()
Gallop answered 29/9, 2021 at 0:42 Comment(1)
what is this doing?Imperceptive
B
-4
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
f = open('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file

How It Works: First, open a file by using the built-in open function and specifying the name of the file and the mode in which we want to open the file. The mode can be a read mode (’r’), write mode (’w’) or append mode (’a’). We can also specify whether we are reading, writing, or appending in text mode (’t’) or binary mode (’b’). There are actually many more modes available and help(open) will give you more details about them. By default, open() considers the file to be a ’t’ext file and opens it in ’r’ead mode. In our example, we first open the file in write text mode and use the write method of the file object to write to the file and then we finally close the file.

The above example is from the book "A Byte of Python" by Swaroop C H. swaroopch.com

Bowel answered 14/7, 2013 at 10:37 Comment(2)
This writes a string to a file, not a list (of strings) as the OP asksTruckage
You need to relate answers to OPs rather more directly than just bolstering your answer number by pasting from other site.Law

© 2022 - 2024 — McMap. All rights reserved.