简体   繁体   English

创建多个* .cfg文件Python

[英]Creating multiple *.cfg files Python

I'm working with *.cfg files. 我正在使用* .cfg文件。 The file can be read in a text editor like gedit and has this format: 可以在文本编辑器(如gedit)中读取该文件,其格式如下:

% some comments
VAR_1= 1
%
% More comments
ANOTHER_VAR= -8
%
% comments again
VAR_THE_COMEBACK= 10

I want to create multiple config files just changing VAR_1= 1....2...3.........10. 我想创建多个配置文件,只需更改VAR_1 = 1 .... 2 ... 3 ......... 10。 I manage to import the *cfg file without any new import in python but I'm not getting a way to change just this parameter, saving the file and creating another one with another value for VAR_1. 我设法导入* cfg文件,而没有在python中进行任何新的导入,但是我没有办法只更改此参数,保存文件并为VAR_1创建另一个具有另一个值的方法。

my code until now is really simple: 到目前为止,我的代码非常简单:

import os

os.chdir('/home/leonardo/Desktop')

f = open('file.cfg','r') #if I replace r by w I erase the file ....
a =  f.read()
print a.find('1')
a.replace('1','2') #I tried this but. ... :(

f.close()

Any tips ? 有小费吗 ?

Thank you for the help ! 感谢您的帮助 !

Untested code, but you will get the idea: 未经测试的代码,但您会明白的:

with open('file.cfg', 'r') as f:
    contents_by_line = f.readlines()
    for var_index, line in enumerate(contents_by_line):
        if line.startswith("VAR_"):
            break
    else:
        raise RuntimeError("VAR_ not found in file")

for var_i, new_cfg_file in ((2,"file2.cfg"),
                              (3, "file3.cfg")): #add files as you want
   with open(new_cfg_file, "w") as fout:
       for i, line in enumerate(contents_by_line):
           if i == var_index:
               fout.write("VAR_1=%d\n" % var_i)
           else:
               fout.write(line)

Thank you guys for all the help. 谢谢大家的帮助。 I changed my approach to the problem, since the lines would be all the 'same', I just created a new line and replaced with a function I found here in stack. 我改变了解决问题的方法,因为这些行都是“相同的”,所以我刚刚创建了一条新行,并替换为在堆栈中找到的函数。 I hope it will help someone someday. 希望有一天能对某人有所帮助。

This script will automate a series of CFD simulations for my final project at college. 该脚本将为我在大学的最终项目自动化一系列CFD模拟。 It creates a series of folders with some simulation conditions on the name, copies the mesh file to the folder created as well as the new config file, the last line will run the code but I need to work in the base simulation setup to run the script. 它会创建一系列带有名称模拟条件的文件夹,将网格文件复制到创建的文件夹以及新的配置文件中,最后一行将运行代码,但我需要在基础模拟设置中运行脚本。

The code is just in preliminary fase, I'll change it to be more readable and to be easily modified. 该代码只是初步的例子,我将其更改为更具可读性和易于修改。

thank you guys ! 感谢大伙们 ! Any tip is welcome, I'm trying to improve my coding skill : ) 欢迎任何提示,我正在尝试提高我的编码技巧:)

the code ::: 编码 :::

import fileinput
import os
import shutil
import subprocess

class stuff:
    root_folder = '/home/leonardo/Desktop/testzone'
    mini_mach = 0.3
    maxi_mach = 1.3
    number_steps = 3
    increment = ((maxi_mach-mini_mach)/number_steps)
    config_file = 'inv_NACA0012.cfg'
    parameter_1 = 'MACH_NUMBER= 0.8'
    parameter_2 = 'CONV_NUM_METHOD_ADJFLOW= JST'
    init_pa = 'MACH_NUMBER= ' #use a space after '='
    init_pa2 = 'CONV_NUM_METHOD_ADJFLOW= ' #use a space after '='
    airfoil = 'NACA0012'
    command1 = 'parallel_computation.py -f ' #use space before the last " ' "
    command2 = '-n 2'
    mesh_file = 'mesh_NACA0012_inv.su2'

class modify:
     def replaceAll(self,files,searchExp,replaceExp):
         for line in fileinput.input(files, inplace=1):
            if searchExp in line:
                line = line.replace(searchExp,replaceExp)
            sys.stdout.write(line)

mod = modify()
stuff = stuff()

for i in xrange(stuff.number_steps):
    mach_name = stuff.airfoil + '_mach_' + `float('%.2f'% stuff.mini_mach)` 
    folder_name = stuff.root_folder + '/' + mach_name
    print 'creating ...' + folder_name
    os.makedirs(folder_name)
    file_father = stuff.root_folder + '/' + stuff.config_file 
    shutil.copy2(file_father,folder_name)
    mesh_father = stuff.root_folder + '/' + stuff.mesh_file
    shutil.copy2(mesh_father,folder_name)
    os.chdir(folder_name)
    pre_mod_file = mach_name + '.cfg'
    os.renames(stuff.config_file,pre_mod_file)
    new_parameter_1 = stuff.init_pa + `float('%.2f'% stuff.mini_mach)`
    new_parameter_2 = stuff.init_pa2 + `float('%.2f'% stuff.mini_mach)`
    mod.replaceAll(pre_mod_file,stuff.parameter_1,new_parameter_1)
    mod.replaceAll(pre_mod_file,stuff.parameter_2,new_parameter_2)
    stuff.mini_mach += stuff.increment
    #subprocess.check_call(stuff.command + pre_mod_file + stuff.command2)

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

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