You are not logged in.
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
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
Or something like:
>>> for i in mylist:
... f.write(str(i)+'\n')
Offline
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
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
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