Demonic
Demonic

Reputation: 55

getting data out of a txt file

I'm only just beginning my journey into Python. I want to build a little program that will calculate shim sizes for when I do the valve clearances on my motorbike. I will have a file that will have the target clearances, and I will query the user to enter the current shim sizes, and the current clearances. The program will then spit out the target shim size. Looks simple enough, I have built a spread-sheet that does it, but I want to learn python, and this seems like a simple enough project...

Anyway, so far I have this:

def print_target_exhaust(f):
    print f.read()

#current_file = open("clearances.txt")
print print_target_exhaust(open("clearances.txt"))

Now, I've got it reading the whole file, but how do I make it ONLY get the value on, for example, line 4. I've tried print f.readline(4) in the function, but that seems to just spit out the first four characters... What am I doing wrong?

I'm brand new, please be easy on me! -d

Upvotes: 2

Views: 150

Answers (3)

kojiro
kojiro

Reputation: 77089

with open('myfile') as myfile: # Use a with statement so you don't have to remember to close the file
    for line_number, data in enumerate(myfile): # Use enumerate to get line numbers starting with 0
        if line_number == 3:
            print(data)
            break # stop looping when you've found the line you want

More information:

Upvotes: 3

Andrew Corsini
Andrew Corsini

Reputation: 1558

Not very efficient, but it should show you how it works. Basically it will keep a running counter on every line it reads. If the line is '4' then it will print it out.

## Open the file with read only permit
f = open("clearances.txt", "r")
counter = 0
## Read the first line 
line = f.readline()

## If the file is not empty keep reading line one at a time
## till the file is empty
while line:
    counter = counter + 1
    if counter == 4
        print line
    line = f.readline()
f.close()

Upvotes: -1

bogatron
bogatron

Reputation: 19169

To read all the lines:

lines = f.readlines()

Then, to print line 4:

print lines[4]

Note that indices in python start at 0 so that is actually the fifth line in the file.

Upvotes: 4

Related Questions