Tyler Simko <tsi...@princeton.edu> writes: > I'm embarrassingly new at Python, so please forgive my probably simple > mistakes.
Welcome, and congratulations on starting with Python! No forgiveness needed for asking questions or making mistakes; the important thing is to learn from both. > So I called readlines() on a file, and I'm wondering how I can check > the equality of a specific line with a raw_input set variable as a > condition. You don't need to use ‘file.readlines’ for this purpose; that method consumes the entire file, which you don't need. You only need the specific line. You could iterate over the file, discarding lines, until you get to the one line you need, and bind a name to just that line. > For example, > > file = open('filename.txt,' 'r') Best not to clobber the built-in name “file”. Choose a more descriptive name for the *purpose* of this value; e.g. “input_file”. > file.readlines() This consumes the entire file, and returns a new sequence containing each line as an item of the sequence. You then throw this new object away, because you haven't bound anything to it. > variable_name = raw_input() > if file[2] == variable_name: > #whatever Again, “variable_name” is utterly opaque as to the purpose. Choose names that clearly indicate what the value *means* in the program. > This approach hasn't worked so far, does anyone have any tips? You're attempting to access an item of the file. But files don't have items that can be indexed that way. Files are, on the other hand, iterable. You get each line of a file by iterating over the file object. (The ‘file.readlines’ method is specific to file objects, and does the entire iteration behind the scenes. That might be what is confusing you.) This is the difference between iterables (objects which you can loop over to get an object each iteration), versus sequences (objects with a sequence of items all present and addressible by index). All sequences are iterable, but not all iterables are sequences. A Python file object is an iterable, but is not a sequence. -- \ “I wish there was a knob on the TV to turn up the intelligence. | `\ There's a knob called ‘brightness’ but it doesn't work.” | _o__) —Eugene P. Gallagher | Ben Finney _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor