您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Python中将数据附加到文本文件的特定行中?

在Python中将数据附加到文本文件的特定行中?

您需要将文件读入内存,修改所需的行并写回文件

temp = open('temp', 'wb')
with open('date.txt', 'r') as f:
    for line in f:
        if line.startswith('February'):
            line = line.strip() + '2012\n'
        temp.write(line)
temp.close()
shutils.move('temp', 'data.txt')

如果您不想使用临时文件

with open('date.txt', 'r+') as f: #r+ does the work of rw
    lines = f.readlines()
    for i, line in enumerate(lines):
        if line.startswith('February'):
            lines[i] = lines[i].strip() + '2012\n'
    f.seek(0)
    for line in lines:
        f.write(line)
python 2022/1/1 18:43:46 有299人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶