在python中的.txt文件中修改一行

时间:2019-12-05 22:49:29

标签: python str-replace findandmodify

因此,我正在尝试修改文本文件中符合条件的多行。 该行将以“ 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)

1 个答案:

答案 0 :(得分:1)

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

            ins.write(line)