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

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

我有几个 .msh 格式的文件,我想使用 python 在其中一些行的末尾添加一个字符串。我的文件名是 mod0.mshmod1.mshmod2.msh 等等。每个文件都有数千行,但第一行是这样的:

$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"
...

我想在某些行的末尾添加另一个字符串 ( new_added_string)。这些行是:

adding_str=[6,7,8,9]

我只对两个文件尝试了以下代码,但它没有给我想要的东西。我还想导出与原始文件格式相同的修改后的文件 (.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)

最后,将字符串添加到提到的行号后,我的文件将如下所示:

$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"
...

我修复了一些错误:

  • for idx in range(2) 缺失 :
  • lines = fin.readline()应该是readlines,否则你只读第一行。
  • 你应该输出line+'new_added_string',而不是只输出'new_added_string'

代码:

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 文件结果:

$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"

您知道 fileinput 用于逐行编辑文件的软件包吗?使用此 处理换行符可能会有所帮助:

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'
            )

当然,就地修改不是必须的,只是一个可能会用到的功能。