zTrusted WF
zTrusted WF

Reputation: 51

read data in txt file and put them into a specific format

What I want to achieve?

• Insert Lat and Long Data into a .txt file (Per line and lat and lon are seperated by "," )

[.txt file]

59.4834, 8.84748

58.4973, 8.38564

• Read data and paste it into a specific format

The Format

<Placement Lat="X" Lon="X" Alt="0#AGL" Hdg="0.0"/>

I want the X`s to be replaced by the data in the .txt file.

If I have 3 lines with coordinates, I want 3 placement outputs each.

Let's assume the text file has 3 lines.

23.8474, 8.5824

25.8474, 9.4735

27.4913, 9.2394

Then the output would be

<Placement Lat="23.8474" Lon="8.5824" Alt="0#AGL" Hdg="0.0"/>

<Placement Lat="25.8474" Lon="9.4735" Alt="0#AGL" Hdg="0.0"/>

<Placement Lat="27.4913" Lon="9.2394" Alt="0#AGL" Hdg="0.0"/>```

Upvotes: 1

Views: 72

Answers (2)

baduker
baduker

Reputation: 20042

Is this what you're looking for?

with open("your_text_file.txt") as text_file:
    lines = [line.strip().split(", ") for line in text_file.readlines() if line.strip()]
    template = '<Placement Lat="{}" Lon="{}" Alt="0#AGL" Hdg="0.0"/>\n'
    print("\n".join(template.format(*line) for line in lines))

Output:

<Placement Lat="23.8474" Lon="8.5824" Alt="0#AGL" Hdg="0.0"/>

<Placement Lat="25.8474" Lon="9.4735" Alt="0#AGL" Hdg="0.0"/>

<Placement Lat="27.4913" Lon="9.2394" Alt="0#AGL" Hdg="0.0"/>

Upvotes: 3

RufusVS
RufusVS

Reputation: 4127

A slightly different approach:

import ast
for lat,lon in map(ast.literal_eval,[x.strip() for x in open("lat_lon.txt","rt") if x.strip()]):
    print (f'<Placement Lat="{lat}" Lon="{lon}" Alt="0#AGL" Hdg="0.0"/>')

Upvotes: 1

Related Questions