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

时间:2018-05-10 08:04:11

标签: python python-3.6 readline

我想在文件的每一行附加一些文字

这是我的代码

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

4 个答案:

答案 0 :(得分:6)

您可以阅读这些行并将它们放入列表中。然后使用写入模式打开相同的文件,并使用要追加的字符串写入每一行。

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)

答案 1 :(得分:3)

假设您可以在内存中加载全文,您可以逐行打开文件,并为每一行添加“#”。然后保存:-):

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

答案 2 :(得分:1)

我假设文件足够小,可以在内存中保留两份副本:

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)

首先,我们打开文件并将所有行读入列表。然后,strip()每行的行终止符生成一个新列表,在其后添加一些额外的文本和一个新的行终止符。

然后,最后一行用新修改的行覆盖文件。

答案 3 :(得分:1)

这有帮助吗?

$.getJSON("C:/Program Files/Sample/demo.json",function (data) {
    $.each(data, function(i, data) {