在 Python 中根据文本拆分文件 [英] Splitting a file based on text in Python

查看:41
本文介绍了在 Python 中根据文本拆分文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件结构如下:

I have a file structured as follows:

Title = "test.txt"  
variables = x,y,z  
zone height=100m  
x1, y1, z1  
...   
xn, yn, zn  
zone height=020m  
x1, y1, z1  
...  
xn, yn, zn  

并且需要将其拆分为多个文件,以 zone height=xxx 行开始.这些输出文件的名称应该是 outfile_xxx.txt,其中 xxx 是高度值.

And need to split this into multiple files starting with the the zone height=xxx lines. The name of these output files should be outfile_xxx.txt where the xxx is the height value.

并不总是只有高度要运行,因此它需要能够根据数量写入任意数量的输出文件

There will not always be only heights to run and so it needs to be able to write an arbitary number of output files based on the number

我一直在尝试下面的方法,现在它几乎按计划工作.我宁愿不为标题编写占位符文件,但想不出跳过标题行的最简单方法

I have been trying the below and now and it is almost working as planned. I would rather not write the placeholder file for the header but can't think of the easiest way to skip the header rows

inp=open(inputfilename)
out=open('zplane_placeholder_for_header.dat','w')

for line in inp:
      if line.startswith("zone"):
        height=line[8:11]
        out.close()
        out=open('zplane'+str(height)+'.dat','w')
      else:
        out.write(line)
out.close()

推荐答案

我已经设法通过以下方式使其对我有用.

I have managed to get this to work for me with the following.

with open (inputfilename) as f:
    next(f)
    next(f)
    for line in f:
      if line.startswith("zone"):
        height=line[8:11]
        next(f)
        out=open('zplane'+str(height)+'.dat','w')
      else:
        out.write(line)
out.close()

这篇关于在 Python 中根据文本拆分文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆