我有以下代码。是的,在我测试代码时,我现在已经删除了很多行。
Actual text from file: forecast= Mostly cloudy and cooler. Precipitation ending with in 6 hours. Windy with possible wind shift to the W NW or N.
当我运行该文件时,它会查找句点以将文本拆分为 5 个不同的变量。 预测 1、预测 2、预测 3、预测 4、预测 5。 它正确地拆分了文件,如不需要的打印命令所示。 我遇到的问题是正确修改现有文本文件 realtimegauges.txt 中的每个新值。 我在文本文件中放置了以下内容: forecast1=大部分多云且凉爽。沉淀在 6 小时内结束。多风,可能风向 W NW 或 N。 forecast2=主要是阵雨和更冷的foecast3=降水将在6小时后结束。 它没有将每个新的(forecastX)变量放在自己的行上。
# safely open the text file we created and search for a string
with open("/home/admin/Documents/realtimegauges.txt",'r') as file:
lines = file.readlines()
for line in lines:
if "forecast=" in line:
str = (line)
forecast1= (str.rsplit('=',1)[1])
forecast2= (forecast1.rsplit('.',5)[0])
try:forecast3= (forecast1.rsplit('.',5)[1])
except IndexError:
forecast3 = ('')
try:forecast4= (forecast1.rsplit('.',5)[2])
except IndexError:
forecast4 = ('')
try:forecast5= (forecast1.rsplit('.',5)[3])
except IndexError:
forecast5 = ('')
print (forecast1)
with open("/home/admin/Documents/realtimegauges.txt",'a') as f:
f.write('forecast1=' + forecast1)
print (forecast2)
with open("/home/admin/Documents/realtimegauges.txt",'a') as f:
f.write('forecast2=' + forecast2)
print (forecast3)
with open("/home/admin/Documents/realtimegauges.txt",'a') as f:
f.write('forecast3=' + forecast3)
f.close()
print (forecast4)
print (forecast5)
#with open("/home/admin/Documents/realtimegauges.txt",'a') as f:
# f.write('forecast1=' + forecast1)
# f.close()
#with open("/home/admin/Documents/realtimegauges.txt",'a') as f:
# f.write('forecast2=' + forecast2)
# f.close()
#with open("/home/admin/Documents/realtimegauges.txt",'a') as f:
# f.write('forecast3=' + forecast3)
# f.close()
#with open("/home/admin/Documents/realtimegauges.txt",'a') as f:
# f.write('forecast4=' + forecast4)
#with open("/home/admin/Documents/realtimegauges.txt",'a') as f:
# f.write('forecast5=' + forecast5)
使用打印到文件
with open("/home/admin/Documents/realtimegauges.txt","a") as f:
print("forecast2=" + (forecast2) ,file=f)
print ("forecast3=" + (forecast3) ,file=f)
print ("forecast4=" + (forecast4) ,file=f)
print ("forecast5=" + (forecast5) ,file=f)