簡體   English   中英

Python 寫入新文件時無法在行尾后的 append 換行符?

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

在下面的方法中,我根據時間戳對文件的內容進行排序,它也可以正常工作但是當我寫入新文件時,我不知道如何 append 換行。它寫在我想要的同一行要更改我的 output 文件中的行,因為輸入非常大,在這種情況下我需要使用塊,因此使用 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)我現在得到的實際 Output

在文件名 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)所需的 Output (我想更改輸入格式中給出的行)

 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]

目前我在同一行得到 output,這對我來說是主要問題嗎?

也許這會有所幫助:

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

writelines() function,盡管它的名字,實際上不會為每一行添加換行符。 (這樣做是為了對應.readlines() function 不會刪除文件中的\n

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM