In python, how do I search for a number in a text file and print a corresponding value when it's found?

I have a list of cam angles and displacements:

<Ignored header>
0   3
1   3
2   6
3   9
4   12
5   15
6   18
7   21
8   24
9   27
10  30
...

How would I go about searching for an angle and producing the displacement at this angle?

It's not necessary to store the data as at any given moment I only need the two values.

I know this isn't currently working, but a brief explanation of why and how to improve would be much appreciated as I'm eager to learn more

camAngle = 140

camFile = open(camFileLoc)
for line in camFile:
    if line > 1:
        if camAngle in line:
        print line

Thanks very much

Lauren

Answers


You basically had it:

camAngle = 140

# The context manager closes the file automatically when you leave the block
with open(camFileLoc, 'r') as handle:
    next(handle)  # Skips the header

    for line in handle:
        # Splits the line on the whitespace and converts each string
        # into an integer. Then, you unpack it into the two variables (a tuple)
        angle, displacement = map(int, line.split())

        if angle == camAngle:
            print displacement
            break  # Exits the `for` loop
    else:
        # We never broke out of the loop, so the angle was never found
        print 'This angle is not in the file'

Need Your Help

ASP Classic VBScript to ASP.NET C# Conversion

c# asp.net .net

I am familiar with ASP.NET, but not with Visual Basic.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.