I have an input file looks like this
test.txt
CAT 396 NUM 59
X Y
4.7642 28.4443
4.7643 28.3640
6.2216 29.0680
6.2217 29.2841
6.4080 28.6427
6.6484 28.6484
CAT 397 NUM 592
X Y
7.0442 23.8320
7.0994 25.9161
7.0995 25.1801
I only need the X and Y coordinate information.
How would I be able to only get the coordinates?
You may try this:
with open('test.txt') as fin :
lines = fin.readlines()
coords = []
for line in lines :
try :
x, y = map( float, line.split())
coords.append( (x,y) )
except ValueError:
pass # ignore other lines
line = 'some words'
if 'word' in line:
# skip/delete the line
If the line you want to skip is always first, you can just skip the first line, without checking the words inside it.
You can use readlines()[2:]
to skip first two lines and then parse numbers. For example: like this
lines = open('test.txt').readlines()[2:]
coords = []
for line in lines:
try:
coords.append(list(map(float, line.split())), lines))
except ValueError:
print(f'ValueError in line: {line}')
print(coords)
It returns:
[[7.0442, 23.832], [7.0994, 25.9161], [7.0995, 25.1801]]
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.