逐行读取文件,并在每个文件上添加新内容

2024-06-16 11:13:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道以前也有人问过类似的问题,但我对python不熟悉,无法找到解决问题的方法:

我想做的是: 1打开一个文件,逐行读取。(我已经做到了) 2在每行后面加上新的东西。(我想稍后将其与if语句结合使用,以便只编辑特定的行)

我的代码:

#!/usr/bin/python3.4

file = open('testfile', 'r+')

readlinebyline = file.readline()

for i in range(0, len(readlinebyline)):
 readlinebyline.write(' ' + 'checked')

print('done')

我希望以后我的测试文件看起来像这样:

line1 checked
line2 checked
line3 checked
...

但它看起来是这样的:

line1
line2
line3
 checked checked checked

如何让程序在每行之后停止,然后添加新内容?你知道吗


Tags: 文件方法代码编辑ifbinusr语句
3条回答
with open('file.txt', 'r') as f:
    content = f.readlines()

with open('file.txt', 'w') as f:
    for line in content:
        f.write(line.strip('\n') + ' checked\n')

我建议逐行将文件写入一个新文件,然后将新文件移动到原始文件,这样会覆盖它:

import shutil

filename = '2017-11-02.txt'
temp_filename = 'new.txt'

with open(filename, 'r') as old, open(temp_filename, 'w') as new:
    # Go line by line in the old file
    for line in old:
        # Write to the new file
        new.write('%s %s\n' % (line.strip(),'checked'))

shutil.move(temp_filename, filename)

有点相关的答案,我基于:https://stackoverflow.com/a/16604958/5971137

你可以利用readlines

with open('testfile', 'r') as file:
    # read a list of lines into data
    lines = file.readlines()

with open('testfile', 'w') as file:
    for line in lines:
        # do your checks on the line..
        file.write(line.strip() + ' checked' )

print('done')

相关问题 更多 >