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
3

4 Answers 4

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Downvoter: please explain so I can improve my answer.
(same struggle here). Happy to learn about that file=fp in the print() method though. Works.
i make it working in my way... reallllllyyyyyyyyyyyyyyyyy great.
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

Comments

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.

Comments

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)

3 Comments

thanks its working. :) but what i want that i want to do such kinda thing in a single file which is created before. mean that want to append in the old created file.
so you want to replace the original file and not create a new file, right?
yeah have got it. tried your provided snippet and modified it too according to my work. Really thanks for indeed help. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.