Python:根据长度约束更改字符串中的内容

时间:2017-11-20 14:09:11

标签: python string python-3.x replace formatting

我正在寻找一种更智能的解决方案来完成我的代码所做的事情。 我必须探索一个文本文件。本文中有许多材料,我想通过用新的值替换这些值来更改一些材料属性。 这是材料结构:

  Material,
    PLASTERBOARD-1,          !- Name
    MediumSmooth,            !- Roughness
    0.01200,                 !- Thickness {m}
    0.16000,                 !- Conductivity {W/m-K}
    950.000,                 !- Density {kg/m3}
    840.00,                  !- Specific Heat {J/kg-K}
    0.900000,                !- Thermal Absorptance
    0.600000,                !- Solar Absorptance
    0.600000;                !- Visible Absorptance

这是我的实际代码:

from tempfile import mkstemp
from shutil import move
from os import fdopen, remove

def update_capacity(idf_file_path, material, capacity):
    check = False
    #Create temp file
    fh, abs_path = mkstemp()
    with fdopen(fh,'w') as new_file:
        with open(idf_file_path) as old_file:
            for line in old_file:
                if material in line:
                    check = True
                if check:
                    if '!- Conductivity {W/m-K}' in line:
                        line = '    '+str(capacity)+ ','
                        i = 26 - len(str(capacity))
                        while(i>0):
                            line +=' '
                            i-=1
                        line += '!- Conductivity {W/m-K}\n'
                        line.strip('(')
                        check= False
                new_file.write(line)
            #Remove original file
            old_file.close()
            new_file.close()
            remove(idf_file_path)
        #Move new file
        move(abs_path, idf_file_path)
    return idf_file_path

mat = 'FIBERGLASS QUILT-1'
cap = 2,0
idf_file = 'D:\\users\\f35943c\\Downloads\\Exercise1A.idf'

update_capacity(idf_file, mat, cap)

if material in linenew_file.write(line)是我想要优化代码的地方。此外,条带不能按我的意愿工作,因为我无法删除线条内的括号。 这是我的基准字符串" 0.16000, !- Conductivity {W/m-K}",我必须尊重!- Conductivity {W/m-K}之前的字符数

有人能带我到更智能的解决方案吗?

2 个答案:

答案 0 :(得分:0)

你可以改写,

if material in line and '!- Conductivity {W/m-K}' in line:
    line = '    '+str(capacity)+ ','
    i = 26 - len(str(capacity))
    while(i>0):
        line +=' '
        i-=1
    line += '!- Conductivity {W/m-K}\n'
    line.strip('(') # Try line.replace('oldvalue', 'newvalue') here
    check= False

new_file.write(line)

答案 1 :(得分:0)

临时解决方案

            if material in line:
                check = True
            if check:
                if '!- Conductivity {W/m-K}' in line:
                    line = '    '+ str(capacity).ljust(25) + '!- Conductivity {W/m-K}\n'
                    check= False
            new_file.write(line)

如果有人有更好的想法,那将是受欢迎的!

我还发现了有关格式化字符串Python 3.x的有用链接:https://www.digitalocean.com/community/tutorials/how-to-use-string-formatters-in-python-3