0

I need to write a python function that reads and stores values from a textfile that looks as follows:

enter image description here

I need to store the variables ncols, nrows….. until NODATA_value, and stop there. So only the first 6 lines are needed. Any tips?

JustANoob
  • 580
  • 1
  • 4
  • 19

3 Answers3

2

Hi this is very simple to do. I recommend you to see a python tutorial. Anyway this can be a start point.:

width open("myfile.txt") as f:
  for idx,line in enumerate(f):
    if idx>=6: break
    #dostuff
Simone
  • 78
  • 1
  • 6
1

I'm sure there are many nice libraries that will do this for you, but it's basic Python to do this without learning new libraries. You can put the contents of the folder into a list: How to read a file line-by-line into a list?

From there, it's easy. Use list.index(element) to find the index of 'ncols', and the index of its value is list.index('ncols')+1. https://www.programiz.com/python-programming/methods/list/index

You could use slicing to crop the list off at NODATA_value: Understanding slice notation

1

You could try something like this:

variables = dict()
with open('my_text_file.txt', 'r') as textfile:
    while True:    
        next_line = textfile.readline()
        if len(next_line) == 0:
            break

        key, value = next_line.split()
        if key == 'NODATA_value':
            break

        variables[key] = value    

This assumes that each line in your file is a key-value pair, where the key and value are separated by some amount of whitespace.

The loop will terminate when the end of the file is reached, or when the NODATA_value key is encountered.

zachdj
  • 354
  • 2
  • 8