基于python中的某些模式将文件拆分为多个文件

时间:2014-08-12 06:07:47

标签: python file

文本文件如下:

shfhsgfkshkjg
gkjsfkgkjfgkfg
model        1
lkgjhllghfjgh
kjfgkjjfghg
endmodel
model        2
jfhkjhcgbkcjg
xhbgkxfkgh
endmodel

我想在每个模型和endmodel之间,文件应该在新文件中是什么。文件名应该像model1,model2 ....模型可能是100或更多。模型和数字之间的空间是8空间正好帮助我。

3 个答案:

答案 0 :(得分:3)

def writeFiles(infilepath):
    outfile = None
    with open(infilepath) as infile:
        for line in infile:
            line = line.strip()
            if line.startswith('model') and outfile is None:
                outfile = open(line, 'w')
                continue
            elif line == 'endmodel':
                outfile.close()
                outfile = None
                continue
            elif outfile is not None:
                outfile.write(line + '\n')

答案 1 :(得分:0)

这应该可以解决问题:

fileName = "text.txt"

inputfile = open(fileName, 'r').readlines()

files = {}
storeContent = False
content = ""
for line in inputfile:
   if "endmodel" in line.strip() and storeContent:
      files [storeContent] = content
      storeContent = False
   elif "model" in line:
      storeContent = line.replace(" ", "").strip()
   elif storeContent:
      if not content:
         content += line
      else:
         content += "\n" + line
   else:
      pass # ignore other content

for name, content in files.items():
   f = open(name + ".txt", "w")
   f.write(content)
   f.close

答案 2 :(得分:0)

You can use below function to do this. This is based on below assumptions:
1. There are some junk characters before first model appears
2. after every endmodel there is model.

def file_read(): path = 'D:\\' file = open(os.path.join(path,'dummy.txt'),'w') k = open('test.txt', 'r') count = 0 for line in k.readlines(): if line.startswith('endmodel'): continue if line.startswith('model'): count += 1 file = open (os.path.join(path,'model' + str(count) + '.txt'),'w') continue file.write(line)

如果这不适合你,请告诉我。