简体   繁体   中英

Append String to each line of .txt file in python?

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

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)

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

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM