Как при записи данных в файл, убрать последний элемент?
У меня есть скрипт:
count = 0
with open('final_1.geojson', 'w') as fin:
fin.write('{"type": "FeatureCollection","features": [')
with open('long_1.txt', 'r') as long:
for i in long:
i_1, i_2 = i.split()
with open('short_1.txt', 'r') as short:
for k in short:
k_1, k_2 = k.split()
string = '{"type": "Feature", "properties": {"area": ' +str(count)+'}, "geometry": {"type": "Polygon", "coordinates": [[['+str(i_1) + ',' + str(k_1)+ ']'+',' + '[' + str(i_2)+','+str(k_1) + ']'+',' + '['+str(i_2)+ ',' + str(k_2) +'],' + '[' + str(i_1)+ ',' + str(k_2) +']]]}},'
fin.write(string)
count+=1
end = ']}'
fin.write(end)
Общая логика такая: Скрипт проходит по файлам, вытягивает из них нужные значения и складывает в новый файл в нужном мне виде.
В скрипте есть перменная string. В конце переменной есть запятая ','
Мне надо, чтобы эта запятая была у всех string, кроме последнего значения.
Сейчас у меня вот так:
"geometry": {"type": "Polygon", "coordinates": [[[5.009,10.005394],[5.01,10.005394],[5.01,10.006293],[5.009,10.006293]]]}},{"type": "Feature", "properties": {"area": 86}, "geometry": {"type": "Polygon", "coordinates": [[[5.009,10.006293],[5.01,10.006293],[5.01,10.007192],[5.009,10.007192]]]}},{"type": "Feature", "properties": {"area": 87}, "geometry": {"type": "Polygon", "coordinates": [[[5.009,10.007192],[5.01,10.007192],[5.01,10.008091],[5.009,10.008091]]]}},{"type": "Feature", "properties": {"area": 88}, "geometry": {"type": "Polygon", "coordinates": [[[5.009,10.008091],[5.01,10.008091],[5.01,10.00899],[5.009,10.00899]]]}},{"type": "Feature", "properties": {"area": 89}, "geometry": {"type": "Polygon", "coordinates": [[[5.009,10.00899],[5.01,10.00899],[5.01,10.009889],[5.009,10.009889]]]}},]}
Должно быть вот так:
"geometry": {"type": "Polygon", "coordinates": [[[5.009,10.005394],[5.01,10.005394],[5.01,10.006293],[5.009,10.006293]]]}},{"type": "Feature", "properties": {"area": 86}, "geometry": {"type": "Polygon", "coordinates": [[[5.009,10.006293],[5.01,10.006293],[5.01,10.007192],[5.009,10.007192]]]}},{"type": "Feature", "properties": {"area": 87}, "geometry": {"type": "Polygon", "coordinates": [[[5.009,10.007192],[5.01,10.007192],[5.01,10.008091],[5.009,10.008091]]]}},{"type": "Feature", "properties": {"area": 88}, "geometry": {"type": "Polygon", "coordinates": [[[5.009,10.008091],[5.01,10.008091],[5.01,10.00899],[5.009,10.00899]]]}},{"type": "Feature", "properties": {"area": 89}, "geometry": {"type": "Polygon", "coordinates": [[[5.009,10.00899],[5.01,10.00899],[5.01,10.009889],[5.009,10.009889]]]}}]}
Посмотрите в конец двух строк.
Вместо '}},]}' в первой строке я хочу сделать '}}]}' для последнего значения.
Как убрать запятую с последнего значения в цыкле?
Ответы (1 шт):
Честно говоря, писать JSON можно гораздо проще, работая с dict.
import json
count = 0
data = {
'type': 'FeatureCollection',
'features': []
}
with open('long_1.txt', 'r') as long:
for i in long:
i_1, i_2 = i.split()
with open('short_1.txt', 'r') as short:
for k in short:
k_1, k_2 = k.split()
data['features'].append({
'type': 'Feature',
'properties': {
'area': str(count),
},
'geometry': {
'type': 'Polygon',
'coordinates': [[
[str(i_1), str(k_1)],
[str(i_2), str(k_1)],
[str(i_2), str(k_2)],
[str(i_1), str(k_2)]
]]
}
})
count += 1
with open('final_1.geojson', 'w') as fin:
fin.write(json.dumps(data))
Upd.
Решение:
Добавить переменную file_is_empty, которая будет говорить нам о том, что в файл мы ничего не записывали, и убрать в конце строки запятую.
При первой итерации - запишется строка без запятой. При второй и последующих итерациях переменная file_is_empty уже будет иметь значение False, а тогда в переменную string добавится запятая в самое начало. По окончанию цикла будет валидный json без проблемной запятой в конце.
count = 0
file_is_empty = True
with open('final_1.geojson', 'w') as fin:
fin.write('{"type": "FeatureCollection","features": [')
with open('long_1.txt', 'r') as long:
for i in long:
i_1, i_2 = i.split()
with open('short_1.txt', 'r') as short:
for k in short:
k_1, k_2 = k.split()
string = '' if file_is_empty else ','
string += '{"type": "Feature", "properties": {"area": ' +str(count)+'}, "geometry": {"type": "Polygon", "coordinates": [[['+str(i_1) + ',' + str(k_1)+ ']'+',' + '[' + str(i_2)+','+str(k_1) + ']'+',' + '['+str(i_2)+ ',' + str(k_2) +'],' + '[' + str(i_1)+ ',' + str(k_2) +']]]}}'
fin.write(string)
file_is_empty = False
count+=1
end = ']}'
fin.write(end)