[英]Modify a line within a .txt file in python
所以我試圖修改滿足條件的文本文件中的多行。 該行將以“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)
請注意,您正在使用文件路徑“f”(一個“str”對象)而不是文件對象“ins”本身。 更改最后一行的變量應該可以解決問題:
ins.write(line)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.