简体   繁体   English

如何在python中几个文件的某些行的末尾添加一个字符串

[英]how to add a string at the end of some lines of several files in python

I have several files with .msh format and want to add a string at the end of some lines of them using python.我有几个.msh格式的文件,想使用 python 在其中的某些行的末尾添加一个字符串。 Name of my files are mod0.msh , mod1.msh , mod2.msh and so on.我的文件名是mod0.mshmod1.mshmod2.msh等等。 Each file has thousands of lines but these is how some first lines look like:每个文件都有数千行,但这些是第一行的样子:

$MeshFormat
2.2 0 8
$EndMeshFormat
$PhysicalNames
13
1 10 "W_1"
1 11 "W_2"
2 8 "fault2"
2 9 "fault1"
2 12 "in"
...

I want to add another string ( new_added_string ) at the end of some lines.我想在某些行的末尾添加另一个字符串( new_added_string )。 These lines are:这些线路是:

adding_str=[6,7,8,9]

I tried the following code for only two files but it did not give me what I wanted.我只为两个文件尝试了以下代码,但它没有给我想要的。 I want to also export modified files with the same format of my original files ( .msh ):我还想导出与我的原始文件 ( .msh ) 格式相同的修改后的文件:

for idx in range(2) # 2 means I have two files:
    with open('changed_{}'.format(idx), 'a') as fout:
        with open('mod{}.msh'.format(idx), 'r') as fin:
            lines = fin.readline()
        for i, line in enumerate (lines):
            if i in exp:
                fout.write(' new_added_string')
            else:
                fout.write(line)

Finally, after adding the string to mentioned line numbers, my file will look like:最后,将字符串添加到提到的行号后,我的文件将如下所示:

$MeshFormat
2.2 0 8
$EndMeshFormat
$PhysicalNames
13
1 10 "W_1" new_added_string
1 11 "W_2" new_added_string
2 8 "fault2" new_added_string
2 9 "fault1" new_added_string
2 12 "in"
...

I fixed some bugs:我修复了一些错误:

  • for idx in range(2) missing : for idx in range(2)缺失:
  • lines = fin.readline() should be readlines , otherwise you only read first line. lines = fin.readline()应该是readlines ,否则你只阅读第一行。
  • you should output line+'new_added_string' , rather than only output 'new_added_string'你应该输出line+'new_added_string' ,而不是只输出'new_added_string'

code:代码:

adding_str = [i-1 for i in [6,7,8,9]]
for idx in range(2): # 2 means I have two files:
    with open('changed_{}.txt'.format(idx), 'a') as fout:
        with open('mod{}.msh'.format(idx), 'r') as fin:
            lines = fin.readlines()
        for i, line in enumerate (lines):
            if i in adding_str:
                fout.write(line.replace("\n","") + ' new_added_string\n')
            else:
                fout.write(line)

change_0.txt file result: change_0.txt文件结果:

$MeshFormat
2.2 0 8
$EndMeshFormat
$PhysicalNames
13
1 10 "W_1" new_added_string
1 11 "W_2" new_added_string
2 8 "fault2" new_added_string
2 9 "fault1" new_added_string
2 12 "in"

Are you aware of the fileinput package for editing files line-wise?您知道用于fileinput编辑文件的fileinput包吗? Using this and handling the linebreaks might help:使用它处理换行符可能会有所帮助:

from fileinput import FileInput


adding_str = [6, 7, 8, 9]

for idx in range(2):
    with FileInput(f'mod{idx}.msh', inplace=True, backup='.bak') as in_file:
        for i, line in enumerate(in_file, start=1):
            print(
                line.rstrip(),
                end=' new_added_string\n' if i in adding_str else '\n'
            )

Of course, the in-place modification is not necessary, just a feature one may use.当然,就地修改不是必须的,只是一个可以使用的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM