修改输出后保留缩进的Python

修改输出后保留缩进的Python,python,indentation,Python,Indentation,我有一个解析文本文件的代码,可以修改文件,但是我需要保留缩进请帮助我保存缩进 这是我的密码: import re import collections class Group: def __init__(self): self.members = [] self.text = [] with open('text1238.txt','r+') as f: groups = collections.defaultdict(Group) gr

我有一个解析文本文件的代码,可以修改文件,但是我需要保留缩进请帮助我保存缩进

这是我的密码:

import re
import collections
class Group:
    def __init__(self):
        self.members = []
        self.text = []

with open('text1238.txt','r+') as f:
    groups = collections.defaultdict(Group)
    group_pattern = re.compile(r'^(\S+)\((.*)\)$')
    current_group = None
    for line in f:
        line = line.strip()
        m = group_pattern.match(line)
        if m:    # this is a group definition line
            group_name, group_members = m.groups()
            groups[group_name].members += filter(lambda x: x not in groups[group_name].members , group_members.split(','))
            current_group = group_name
        else:
            if (current_group is not None) and (len(line) > 0):
                groups[current_group].text.append(line)
    f.seek(0)
    f.truncate()

    for group_name, group in groups.items():
        f.write("%s(%s)" % (group_name, ','.join(group.members)))
        f.write( '\n'.join(group.text) + '\n')
输入Text.txt

 Car(skoda,audi,benz,bmw)
     The above mentioned cars are sedan type and gives long rides efficient
 ......

Car(Rangerover,audi,Hummer)
     SUV cars are used for family time and spacious.
预期输出Text.txt

 Car(skoda,audi,benz,bmw,Rangerover,Hummer)
     The above mentioned cars are sedan type and gives long rides efficient
 ......
     SUV cars are used for family time and spacious.
但将输出作为:

Car(skoda,audi,benz,bmw,Rangerover,Hummer)
The above mentioned cars are sedan type and gives long rides efficient
......
SUV cars are used for family time and spacious.
如何保留缩进? 请帮我修改代码!答案将不胜感激

您需要更换:

groups[current_group].text.append(line)
与:


这将为缩进添加选项卡。或者,如果需要空格,您可以使用
'
(四个空格),如果
'\t'
问题是
line=line.strip()
。这将删除压痕。删除该行应该保留缩进,尽管您可能需要调整正则表达式(但不适用于显示的代码)。

读取输入文件时,需要在该行上执行strip()。这将从行的开头和结尾删除任何空格、制表符。也许你应该使用rstrip(),它只会删除尾随的空格。你可以把r.strip()放到我的代码中吗?我不知道在哪里解决这个问题?我应该在哪里使用它?line=line.strip()#更改这个m=group_模式。match(line)
groups[current_group].text.append('\t' + line)