Python 写入新文件时无法在行尾添加换行符?

Python Not able to append new line character after the end of a line when writing to a new file?

在下面的方法中,我根据时间戳对文件的内容进行排序,它也工作正常 但是当我写新的 file.It 时我不知道如何追加新行正在写在同一行我想更改输出文件中的行因为输入非常大我需要使用块在这种情况下 所以使用 readlines 或存储在任何数据结构中都不会在这里工作

1)我的输入文件格式如下

TIME[04.26_12:30:30:853664]  ID[ROLL:201987623]  MARKS[PHY:100|MATH:200|CHEM:400]
TIME[03.27_12:29:30.553669]  ID[ROLL:201987623]  MARKS[PHY:100|MATH:1200|CHEM:900]
TIME[03.26_12:28:30.753664]  ID[ROLL:2341987623] MARKS[PHY:100|MATH:200|CHEM:400]
TIME[03.26_12:29:30.853664]  ID[ROLL:201978623]  MARKS[PHY:0|MATH:0|CHEM:40]
TIME[04.27_12:29:30.553664]  ID[ROLL:2034287623] MARKS[PHY:100|MATH:200|CHEM:400]

代码如下

import re
from functools import partial
from itertools import groupby
from typing import Tuple

regex = re.compile(r"^.*TIME\[([^]]+)\]ID\[ROLL:([^]]+)\].+$")
def func1(arg) -> bool:
    return regex.match(arg)


def func2(arg) -> Tuple[str, int]:
    match = regex.match(arg)
    if match:
        return match.group(1), int(match.group(2))
    return "", 0

def func3(arg) -> int:
    match = regex.match(arg)
    if match:
        return int(match.group(2))
    return 0

def read_in_chunks(file_object, chunk_size=1024*1024):
    while True:
        data = file_object.read(chunk_size)
        if not data:
            break
        yield data

with open('b.txt') as fr:
    for chunk in read_in_chunks(fr):
        collection = filter(func1, chunk.splitlines())
        collection = sorted(collection, key=func2)
        for key, group in groupby(collection, key=func3):
            with open(f"ROLL_{key}", mode="wa") as fw:
                fw.writelines(group)# want suggestions to append newline character before every line

2)我现在得到的实际输出

在文件名中ROLL_201987623.txt

 TIME[03.27_12:29:30.553669]  ID[ROLL:201987623]  MARKS[PHY:100|MATH:1200|CHEM:900]  TIME[04.26_12:30:30:853664]  ID[ROLL:201987623]  MARKS[PHY:100|MATH:200|CHEM:400]

3) 所需的输出(我想更改输入格式中给定的行)

 TIME[03.27_12:29:30.553669]  ID[ROLL:201987623]  MARKS[PHY:100|MATH:1200|CHEM:900]  
 TIME[04.26_12:30:30:853664]  ID[ROLL:201987623]  MARKS[PHY:100|MATH:200|CHEM:400]

目前我在同一行中得到输出,这是我的主要问题?

也许这会有所帮助:

#  suggestions to append newline character before every line
group = map(lambda x: x + '\n', group)
fw.writelines(group)

writelines()函数,不管它的名字,实际上不会在每一行中添加一个换行符。 (这样做是为了对应 .readlines() 函数,该函数不会删除文件中的 \\n

我建议使用 fw.writelines([i+'\n' for i in group]) 手动添加必要的换行符。