-4

I have a text file that looks like this:

1,004,59
1,004,65
1,004,69
1,005,55
1,005,57
1,006,53
1,006,59
1,007,65
1,007,69
1,007,55
1,007,57
1,008,53

Want to create new text file that will be inserted by 'input', something like this

1,004,59,input
1,004,65,input
1,004,69,input
1,005,55,input
1,005,57,input
1,006,53,input
1,006,59,input
1,007,65,input
1,007,69,input
1,007,55,input
1,007,57,input
1,008,53,input

I have attempted something like this:

with open('data.txt', 'a') as f:
    lines = f.readlines()
    for i, line in enumerate(lines):
            line[i] = line[i].strip() + 'input'
    for line in lines:
        f.writelines(line)

Not able to get the right approach though.

Shubham Kuse
  • 135
  • 1
  • 2
  • 10

3 Answers3

2

What you want is to be able to read and write to the file in place (at the same time). Python comes with the fileinput module which is good for this purpose:

import fileinput

for line in fileinput.input('data.txt', inplace=True):
    line = line.rstrip()
    print line + ",input"

Discusssion

The fileinput.input() function returns a generator that reads your file line by line. Each line ends up with a new line (either \n or \r\n, depends on the operating system).

The code then strip off each line of this new line, add the ",input" part, then print out. Note that because of fileinput magic, the print statement's output will go back into the file instead of the console.

Hai Vu
  • 37,849
  • 11
  • 66
  • 93
1

There are a newline '\n' in every line in your file, so you should handle it. edit: oh I forgot about the rstrip() function!

tmp = []
with open("input.txt", 'r') as file:
    appendtext = ",input\n"
    for line in file:
        tmp.append(line.rstrip() + appendtext)

with open("input.txt", 'w') as file:
        file.writelines(tmp)

Added:

Answer by Hai_Vu is great if you use fileinput since you don't have to open the file twice as I did.

0

To do only the thing you're asking I would go for something like

newLines = list()
with open('data.txt', 'r') as f:
    lines = f.readlines()

    for line in lines:
        newLines.append(line.strip() + ',input\n')

with open('data2.txt', 'w') as f2:
    f2.writelines(newLines)

But there are definitely more elegant solutions

FishySwede
  • 1,563
  • 1
  • 17
  • 24