简体   繁体   English

将字符串附加到python中.txt文件的每一行?

[英]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. 然后,通过strip()从每一行中的行终止符生成一个新列表,在其后添加一些额外的文本和一个新的行终止符。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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