简体   繁体   中英

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. Currently my code looks line this but am getting the following error "AttributeError: 'str' object has no attribute '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. Changing the variable of the last line should do the trick:

            ins.write(line)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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