【问题标题】:Modify a line within a .txt file in python在 python 中修改 .txt 文件中的一行
【发布时间】:2020-03-30 22:19:01
【问题描述】:

所以我试图修改文本文件中符合条件的多行。 该行将以“Section”开头,然后我将对行进行一些修改,然后我想用新行替换旧行。目前我的代码看起来像这样,但收到以下错误“AttributeError:'str'对象没有属性'write'”

for f in glob.glob('*.svp'):
    print(f)
    with open(f,'r+') as ins:
        fileArray = []
        for line in ins:
            fileArray.append(line)
            if "Section" in line:
                lat = line[26:35]
                lineToKeep = line[:33] #Portion of line without lat.## lon, what will be amended
                latAmended = round(float(lat[7:])*0.6)
                latAmended = str(latAmended).zfill(2)
                lon = line[36:46]
                lonToKeep = lon[:-2]
                lonAmended = round(float(lon[8:])*0.6)
                lonAmended = str(lonAmended).zfill(2)
                goodStuff = lineToKeep + latAmended + ' '+ lonToKeep + lonAmended
                line = goodStuff
            f.write(line)

【问题讨论】:

  • 变量和函数名应该遵循lower_case_with_underscores风格。

标签: python str-replace findandmodify


【解决方案1】:

请注意,您使用的是文件路径“f”(一个“str”对象)而不是文件对象“ins”本身。更改最后一行的变量应该可以解决问题:

            ins.write(line)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-28
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 2014-02-08
    • 1970-01-01
    相关资源
    最近更新 更多