使用文本文件中包含的某些标签将文件拆分为单独的文件

时间:2014-05-27 11:03:49

标签: python

我有一个通过组合单独文件的内容创建的文本文件。我现在想扭转这种局面。让我举几个例子:

ID:t-599108
===================
===================
===================
ID:t-599108
===================
===================
===================
ID:t-594356
===================
===================
===================
ID:t-594356
===================
===================
===================
ID:t-594356
===================
===================

=========是ID之后的文本。我想使用ID将文件分成不同的文件。请在文件中重复ID。生成的文件将使用ID命名。我可以使用Python或任何其他语言实现这一目标吗?谢谢

1 个答案:

答案 0 :(得分:0)

确定:

lines = """your massive body of text""".splitlines()
text = ""
id = ""
for line in lines:
  if "ID:" in line:
    if id != "": # previously existed, then save to file
      id = line[3:]
      open(id + ".txt").write(text) # write to a file like "t-111.txt"  
    id = line[3:] # take id
    text = "" # reset text
  else:
    text += line