Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #19843 > unrolled thread
| Started by | Nick Dokos <nicholas.dokos@hp.com> |
|---|---|
| First post | 2012-02-03 15:47 -0500 |
| Last post | 2012-02-03 15:47 -0500 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Help writelines Nick Dokos <nicholas.dokos@hp.com> - 2012-02-03 15:47 -0500
| From | Nick Dokos <nicholas.dokos@hp.com> |
|---|---|
| Date | 2012-02-03 15:47 -0500 |
| Subject | Re: Help writelines |
| Message-ID | <mailman.5419.1328302606.27778.python-list@python.org> |
Anatoli Hristov <tolidtm@gmail.com> wrote:
> Hi everyone,
>
> I`m totaly new in python and trying to figure out - how to write a list to a file with a newline at the end of each object.
> I tried alot of combinations :) like:
> users = ['toli','didi']
> fob=open('c:/Python27/Toli/username','w')
> fob.writelines(users) + '%s\N'
> fob.close()
> or fob.writelines('\N' % users)
> or fob.writelines('%s\N' % users)
> but nothing of dose works...
>
> Could you help me find out the right syntaxes?
>
>From the docs:
| writelines(...)
| writelines(sequence_of_strings) -> None. Write the strings to the file.
|
| Note that newlines are not added. The sequence can be any iterable object
| producing strings. This is equivalent to calling write() for each string.
So *you* need to add the newlines, e.g. you can use a list comprehension:
fob.writelines(["%s\n" % (x) for x in users])
or write in a loop:
for u in users:
fob.write("%s\n" % (u))
or join the list elements together with a newline separator (but you'll
need to add a final newline by hand):
fob.writelines("\n".join(users) + "\n")
or ...
Nick
Back to top | Article view | comp.lang.python
csiph-web