4

I want to append some text to every line in my file

Here is my code

filepath = 'hole.txt'
with open(filepath) as fp:
    line = fp.readline()
    cnt = 1
    while line:
        #..........
        #want to append text "#" in every line by reading line by line 
        text from .txt file
        line = fp.readline()
        cnt += 1
DavidG
  • 24,279
  • 14
  • 89
  • 82

4 Answers4

14

You can read the lines and put them in a list. Then you open the same file with write mode and write each line with the string you want to append.

filepath = "hole.txt"
with open(filepath) as fp:
    lines = fp.read().splitlines()
with open(filepath, "w") as fp:
    for line in lines:
        print(line + "#", file=fp)
Maxime Chéramy
  • 17,761
  • 8
  • 54
  • 75
6

Assuming you can load the full text in memory, you could open the file, split by row and for each row append the '#'. Then save :-) :

with open(filepath, 'r') as f:     # load file
    lines = f.read().splitlines()  # read lines

with open('new_file.txt', 'w') as f: 
    f.write('\n'.join([line + '#' for line in lines]))  # write lines with '#' appended
arnaud
  • 3,293
  • 1
  • 10
  • 27
1

I'll assume the file is small enough to keep two copies of it in memory:

filepath = 'hole.txt'
with open(filepath, 'r') as f:
    original_lines = f.readlines()

new_lines = [line.strip() + "#\n" for line in original_lines]

with open(filepath, 'w') as f:
    f.writelines(new_lines)

First, we open the file and read all lines into a list. Then, a new list is generated by strip()ing the line terminators from each line, adding some additional text and a new line terminator after it.

Then, the last line overwrites the file with the new, modified lines.

agubelu
  • 399
  • 1
  • 7
1

does this help?

inputFile = "path-to-input-file/a.txt"
outputFile = "path-to-output-file/b.txt"
stringToAPpend = "#"

with open(inputFile, 'r') as inFile, open(outputFile, 'w') as outFile:
    for line in inFile:
        outFile.write(stringToAPpend+line)
Ankush Rathi
  • 622
  • 1
  • 6
  • 26