Python 3 - 从ASCII文件中复制一段文本

时间:2015-07-03 21:10:33

标签: python-3.x

我想从ASCII文件中复制一段文本。

例如,从行:

*ELEMENT, TYPE=S3, ELSET=DAM

直到行:

*ELEMENT, TYPE=S4, ELSET=WALL

,然后将其写入新的ASCII文件中。

你能解释一下我的意思吗?

...
*NODE, NSET=NEW
1,  3., 4., 5.
2,  6., 1., 4.
1,  3., 4., 5.
2,  6., 1., 4.
*ELEMENT, TYPE=S3, ELSET=DAM
1,  1,  2,  3
2,  4,  5,  6
...
*ELEMENT, TYPE=S4, ELSET=WALL
11, 10, 20, 30
25, 40, 50, 60
...

2 个答案:

答案 0 :(得分:1)

打开文件,读取直到你到达起始行,写下该行然后使用内部循环,直到你到达终点然后结束函数:

def get_section(in_f, out_f, start, end):
    with open(in_f) as f, open(out_f,"w") as out:
        for line in f:
            if line.strip() == start:
                out.write(line)
                for line in f:
                    if line.strip() == end:
                        out.write(line)
                        return
                    out.write(line)
get_section("in.txt","out.txt","*ELEMENT, TYPE=S3, ELSET=DAM","*ELEMENT, TYPE=S4, ELSET=WALL")

答案 1 :(得分:0)

Hi all
Well my initial question was incomplete. 
In fact my objectif is to find out some given 
block of text having a given pattern. In example 
below, I try to get all blocks starting with *ELEMENT 
till the line starting with *ANYTHING
...
** I am a comment
*NODE
1,  3., 4., 5.
2,  6., 1., 4.
1,  3., 4., 5.
2,  6., 1., 4.

*ELEMENT, TYPE   =   S3,            ELSET=DAM
1,  1,  2,  3
2,  4,  5,  6
*NODE
10,  3., 4., 5.
20,  6., 1., 4.
*ELEMENT, TYPE=S4, ELSET=WALL
11, 10, 20, 30
25, 40, 50, 60
*NODE, NSET         =SOMETHING_ELSE
100,  3., 4., 5.
*ELEMENT          , TYPE   =   S4, ELSET=WALL2
11, 10, 20, 30
25, 40, 50, 60
...

Finally I have modified the code from Padraic as following 
to get blocks from randomly written input deck. It may 
interest at least FEM engineers so here it is. 
If you have a more elegent solution I will appreciate it.
Remote Device