I'm trying to find max and min values from a text file which contains data in rows and columns. But I want to create a script which will skip the first couple of lines and calculate the max and min from there on. I am aware for the max and min functions in Python, but I'm not sure how to specify the range. I know I can do something like the following:

f = open('data.txt', 'r') # Open file

data = f.readlines() # Read lines in the file

for range(2,...): # Define the range. Is there a way to not close the range? 
                  # I mean, I don't want to specify an end for the range.
    max(data)
    min(data)

print max(data), min(data)

Apologies for any mistakes as I am new to Python.

You should iterate lines of file, not range. Inside you can test that line is a interesting one or not. Alternately you could split whole file (after reading the first few lines in for loop with next or readline method) to words and iterate them skipping the words that are not numbers with try,..except.

So I should be specifying which lines I want to read in the readlines() function?

You can slice off the first two records.

f = open('data.txt', 'r') # Open file
 
data = f.readlines()
data = data[2:]
f.close()

print max(data), min(data)

but this may or may not give you what you want depending on the values and type of values in data.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.