(python) for some reason file.readline() is only reading every second line

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • david2031
    New Member
    • Oct 2011
    • 4

    (python) for some reason file.readline() is only reading every second line

    why is this skipping readlines in what it returns? i went through debugger and found it thinks the second line of the txt file is the first and continues to skip every second line.
    Code:
    def get_distances(filename):
        opener = open(filename)
        d = {}
        while file.readline(opener) != '':
            '''converts a file with cities and distances into a dictionary with values
            of distances from one city to other cities and then stores that dictionary
            in a list with values specific to each city
            '''
            #storing the line which has been read in a list
            read = file.readline(opener)
            my_list = read.split(":")
            my_list[1] = my_list[1].split()
    
            max = len(my_list[1]) - 1
            my_list.append(my_list[1][max])
            my_list[1].pop()
    
            if max > 1:
                my_list[1] = my_list[1][0] + ' ' + my_list[1][1]
            else:
                my_list[1] = my_list[1][0]
            print my_list
            if d.has_key(my_list[0]):
                d[my_list[0]].append((my_list[1],my_list[2]))
            else:
                d[my_list[0]] = [(my_list[1],my_list[2])]
        return d
    print get_distances('cities.txt')
    and it returns. i put the print of my_list in there to illustrate how it skips lines.
    Code:
    ['New York', 'Washington', '2']
    ['San Francisco', 'Mexico City', '3']
    ['Toronto', 'San Francisco', '6']
    {'Toronto': [('San Francisco', '6')], 'San Francisco': [('Mexico City', '3')], 'New York': [('Washington', '2')]}
    and etc. depending on how many more cities i add to the txt file. any suggestions on how to solve this problem?
    my text file is 'cities.txt'
    Code:
    Toronto:New York 3
    New York:Washington 2
    Washington:San Francisco 5
    San Francisco:Mexico City 3
    Toronto:Mexico City 7
    Toronto:San Francisco 6
    Attached Files
  • david2031
    New Member
    • Oct 2011
    • 4

    #2
    i realize i the while statement reads it once everytime the loop goes through thus skipping the line. sorry for waste.

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      Instead of using readline(), try iterating on the file object as in:
      Code:
      f = open("filename.txt")
      for line in f:
          .... do stuff ...
      f.close()

      Comment

      • david2031
        New Member
        • Oct 2011
        • 4

        #4
        i am just learning python so some obvious things i are not so obvious to me. for that project i ended up making two opens for the same file but as of now i have updated myself on how and when to use for loops. thanks.

        Comment

        • Buzzer159
          New Member
          • Dec 2020
          • 1

          #5
          I realize the original post is 9 years old (LOL!) but it was the only thing that Google threw up for the problem I encountered when converting a program from csv processing to flat file processing.

          I ended up with;
          =============== ===============

          # Open the file
          f = open(inputfile, "r") #
          #
          # Read the file and process the data
          #
          for row in f:
          row = f.readline() # Read a record
          ETC.
          =============== =============== =====

          Which as the OP notes, results in the program reading record 2,4,6,8 etc

          And the same applies if you use 'for x in f' or whatever.

          I tried a couple of things then eventually commented out the readline statement completely

          =============== =============== ========

          # Open the file
          f = open(inputfile, "r") #
          #
          # Read the file and process the data
          #
          for row in f:
          # row = f.readline() # Read a record
          ETC.
          =============== =============== =====

          And it worked! Weird. So there's an implied read somewhere in that for statement ('cos there ain't one in my code!

          Hope this helps some fellow traveller :-)

          Comment

          Working...