You are not logged in.

#1 2009-07-12 00:43:38

B4RR13N705
Member
Registered: 2009-06-08
Posts: 87

Saving a python list into a file.

Hi, i was wondering one thing:
how to save a python list into a file.
For example, i have:

mylist = [1, 2 ,6 ,56, 78]

And i want to save them on a text file so the text file looks like this:

1
2
6
56
78

I mean, every value below the other.
I tried some stuff like

f = open("myfile", "w")
f.write(mylist)

But it save it as one long string and not one below the other.


OS -----> Arch Linux     DE -----> KDE4
CPU ---> 2.66GHz         RAM ---> 512 MB
SWAP -> 2 G                / -------> 10 G
/home -> 50 G             /boot ---> 64 MB

Offline

#2 2009-07-12 01:09:03

BetterLeftUnsaid
Member
From: My Happy Place
Registered: 2007-11-04
Posts: 78

Re: Saving a python list into a file.

f = open("myfile", "w")
mylist = [1, 2 ,6 ,56, 78]
f.write("\n".join(map(lambda x: str(x), mylist)))
f.close()

The above converts all the items in mylist to a string, and then joins them with the newline character before writing to the file.  It doesn't have a trailing newline, though, so if you want the file to end with a newline:

f.write("\n".join(map(lambda x: str(x), mylist)) + "\n")

Use that instead.

Last edited by BetterLeftUnsaid (2009-07-12 01:09:37)

Offline

#3 2009-07-12 01:24:53

marxav
Member
From: Gatineau, PQ, Canada
Registered: 2006-09-24
Posts: 386

Re: Saving a python list into a file.

Or something like:
>>> for i in mylist:
...     f.write(str(i)+'\n')

Offline

#4 2009-07-12 02:03:14

Dusty
Schwag Merchant
From: Medicine Hat, Alberta, Canada
Registered: 2004-01-18
Posts: 5,986
Website

Re: Saving a python list into a file.

BetterLeftUnsaid wrote:
f = open("myfile", "w")
mylist = [1, 2 ,6 ,56, 78]
f.write("\n".join(map(lambda x: str(x), mylist)))
f.close()

Map is kind of "unofficially deprecated" (along with filter and reduce); use generator expressions instead:

f.write("\n".join(str(x) for x in mylist))

Dusty

Offline

#5 2009-07-12 02:06:23

BetterLeftUnsaid
Member
From: My Happy Place
Registered: 2007-11-04
Posts: 78

Re: Saving a python list into a file.

Dusty wrote:

Map is kind of "unofficially deprecated" (along with filter and reduce); use generator expressions instead:

f.write("\n".join(str(x) for x in mylist))

Dusty

I was kind of thinking that when I wrote it, but I wasn't too sure.

Curse my tendency to overly complicate things =/

Offline

#6 2009-07-12 02:46:34

B4RR13N705
Member
Registered: 2009-06-08
Posts: 87

Re: Saving a python list into a file.

BetterLeftUnsaid wrote:
f = open("myfile", "w")
mylist = [1, 2 ,6 ,56, 78]
f.write("\n".join(map(lambda x: str(x), mylist)))
f.close()

This works perfectly! thanx!


OS -----> Arch Linux     DE -----> KDE4
CPU ---> 2.66GHz         RAM ---> 512 MB
SWAP -> 2 G                / -------> 10 G
/home -> 50 G             /boot ---> 64 MB

Offline

Board footer

Powered by FluxBB