Skip to content
Advertisement

Appending each element of list at the end of file lines

I wrote this code.. However i can’t append elements at the end of line.. the output is just as this..

JavaScript

What changes does my code requires?

Advertisement

Answer

You can’t append to lines within a file without moving other data out of the way.

If you can slurp the whole file into memory, this can be done without too much hassle by rewriting the file in place:

JavaScript

This will not work as expected if the line count and length of alist differ (it will drop lines); you could use itertools.zip_longest (izip_longest on Py2) to use a fill value for either side, or use itertools.cycle to repeat one of the inputs enough to match.

If the file won’t fit in memory, you’ll need to use fileinput.input with inplace=True or manually perform a similar approach by writing the new contents to a tempfile.NamedTemporaryFile then replacing the original file with the tempfile.

Update: Comments requested a version without zip or str.format; this is identical in behavior, just slower/less Pythonic and avoids zip/str.format:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement