Python在修改输出时保留缩进

时间:2014-08-17 13:46:09

标签: 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)
    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')

INPUT 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.

我如何保留缩进? 请帮我修改我的代码!答案将不胜感激!

2 个答案:

答案 0 :(得分:2)

问题是line = line.strip()。这将删除缩进。删除该行应该保留缩进,尽管您可能需要调整正则表达式(但不是为了显示的代码)。

答案 1 :(得分:0)

您需要替换:

groups[current_group].text.append(line)

使用:

groups[current_group].text.append('\t' + line)

这将为缩进添加标签。或者,如果您想要空格,则可以使用' '(四个空格)代替'\t'