-1

My objective or output I'm looking for is to append to input txt file the first part of all lines of existing input file. As an example:

Input:
line_item1 string1
line_item2 string2
line_item3 string3

Output:
line_item1 string1
line_item2 string2
line_item3 string3
line_item1   # append
line_item2   # append
line_item3   # append

The code I have created does not output anything:

portionA = []
with open('output outfile.txt', "a+") as f:
    for line in f.readlines():
        parts = line.strip().split("\t", 1)
        portionA = parts[0]
        portionB = parts[1]
        portionA.append(line)
        f.write('{}\n'.format(''.join(portionA)))   
Vincent Savard
  • 34,979
  • 10
  • 68
  • 73
user1739581
  • 85
  • 2
  • 14

2 Answers2

1

You can try:

with open('output outfile.txt', "a+") as f:
    for line in f.readlines():
        parts = line.strip().split("\t")
        f.write('{}\n'.format(parts[0])) 
0

You should use 'r+' instead of 'a+'.

``r+''  Open for reading and writing.  The stream is positioned at the
         beginning of the file.

Why a+ doesn't work is discussed here

I can't correct the indents on your code for the f.write so here's the corrected snippet (Note the join with \n instead of empty string)

writeList= []
with open('outfile.txt', "r+") as f:
    for line in f:
        parts = line.strip().split("\t", 1)
        portionA = parts[0]
        portionB = parts[1]
        writeList.append(line)
    f.write('{}\n'.format('\n'.join(writeList)))
Community
  • 1
  • 1
Obsidian
  • 515
  • 3
  • 10