2

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?

B.Joelene
  • 133
  • 1
  • 2
  • 7
  • What is the output you are trying to achieve? – dirn Dec 28 '15 at 20:26
  • You're asking to edit the strings of a file, which is different than appending to the file. This question should help: http://stackoverflow.com/questions/39086/search-and-replace-a-line-in-a-file-in-python – Jeremy Fisher Dec 28 '15 at 20:34
  • "append" mode means everytime you write to the file, the file cursor gets moved to the end of the file before writing. – spectras Dec 28 '15 at 20:34
  • 1
    You need to write the original line + whatever you want to add each iterations, either write to a tempfile or use fileinput http://stackoverflow.com/questions/34496769/search-the-word-and-replace-the-whole-line-containing-the-word-in-a-file-in-pyt/34497007#34497007 – Padraic Cunningham Dec 28 '15 at 20:36
  • Do you want to change the original file or generate a new outputfile? – timgeb Dec 28 '15 at 20:43
  • @timgeb i want to generate the original file.. however i'm looking for doing it only iterations as much as possible not using different methods. :) – B.Joelene Dec 28 '15 at 22:09
  • @PadraicCunningham hai ! i want to ask can i do these operations without sys library? – B.Joelene Dec 28 '15 at 22:12
  • @B.Joelene, yes you can use print too http://stackoverflow.com/questions/29452879/python-delete-lines-of-text-line-1-till-regex/29452914#29452914 http://stackoverflow.com/questions/30313920/removing-text-from-a-text-file/30313997#30313997 – Padraic Cunningham Dec 29 '15 at 01:12

1 Answers1

2

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
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • Thank you ShadowRanger! I want to ask you if there is a way without using format and zip? – B.Joelene Dec 28 '15 at 22:49
  • @B.Joelene: I mean, there are always ways to do so, but they're less Pythonic and more verbose. `zip` and `str.format` are both Python builtins, no import required, and they're usually very fast. If you don't want to use them, you can avoid them, but you need to handle all the corner cases (mismatched input lengths for `zip`, non-`str` values for output for `str.format`) manually. – ShadowRanger Dec 28 '15 at 23:06