gpt4 book ai didi

python 对现有文件进行更改

转载 作者:太空宇宙 更新时间:2023-11-03 18:13:50 27 4
gpt4 key购买 nike

我有一段代码可以解析文本文件并将其打印在stdout上,但我需要对现有文本文件进行更改保留缩进

这是我的代码:

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

with open('text1.txt') 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)

for group_name, group in groups.items():
print "%s(%s)" % (group_name, ','.join(group.members))
print '\n'.join(group.text)
print

输入文本.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.

预期输出文本.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.

如何保留缩进?

最佳答案

正如您在 python documentation 中所读到的那样,使用 open 打开文件并使用修饰符 w 截断文件并允许写入,然后写入文件:

with open('text1.txt', 'w') as f:
for group_name, group in groups.items():
f.write("%s(%s)" % (group_name, ','.join(group.members)))
f.write('\n'.join(group.text) + '\n')

您还可以使用 r+ 打开该文件一次,以允许读写和更改代码,如下所示:

with open('text1.txt', 'r+') as f:
groups = ...
...
... groups[current_group].text.append(line)

f.seek(0) # move the cursor to the beginning of the file
f.truncate() # deletes everything from the file

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

关于python 对现有文件进行更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25349037/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com