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..

file:  AGA ABA
       ABA ATA 
       ACA ARA

alist=[1,2,3]

def write_file():
    for item in alist:
        in_file_with_append_mode.write(str(item) + "n")

in_file_with_append_mode=open("file.txt","a")
write_file()

the output is:

AGA ABA
ABA ATA
ACA ARA
1
2 
3

expected output:
AGA ABA  1 
ABA ATA  2
ACA ARA  3

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:

alist=[1,2,3]

# Open for read/write with file initially at beginning
with open("file.txt", "r+") as f:
    # Make new lines
    newlines = ['{} {}n'.format(old.rstrip('n'), toadd) for old, toadd in zip(f, alist)]
    f.seek(0)  # Go back to beginning for writing
    f.writelines(newlines)  # Write new lines over old
    f.truncate()  # Not needed here, but good habit if file might shrink from change

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:

# Open for read/write with file initially at beginning
with open("file.txt", "r+") as f:
    lines = list(f)
    f.seek(0)
    for i in range(min(len(lines), len(alist))):
        f.write(lines[i].rstrip('n'))
        f.write(' ')
        f.write(str(alist[i]))
        f.write('n')
    # Uncomment the following lines to keep all lines from the file without
    # matching values in alist
    #if len(lines) > len(alist):
    #    f.writelines(lines[len(alist):])
    f.truncate()  # Not needed here, but good habit if file might shrink from change
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement