简体   繁体   English

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

[英]Modify a line within a .txt file in python

So I am trying to modify multiple lines within a text file that meet a criteria.所以我试图修改满足条件的文本文件中的多行。 The line will start with "Section", and then I will do some modifying to the line, then I would like to replace the old line with the new line.该行将以“Section”开头,然后我将对该行进行一些修改,然后我想用新行替换旧行。 Currently my code looks line this but am getting the following error "AttributeError: 'str' object has no attribute 'write'"目前我的代码看起来像这样,但出现以下错误“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)

Notice that you are using the file path 'f' (a 'str' object) instead of the file object 'ins' itself.请注意,您正在使用文件路径“f”(一个“str”对象)而不是文件对象“ins”本身。 Changing the variable of the last line should do the trick:更改最后一行的变量应该可以解决问题:

            ins.write(line)

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

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