0
def load_from_file():
    d = {}  # create empty dict 
    file = open("players.txt", "r")# open file for reading
    line = file.readline()
    file.close()# we’re done with the file
    list = line.split(",")
    prop = {"position":"","number":"","name":"","birth":"","id":""}
    keys = (sorted(prop))
    num = 0
    for key in keys:
        d[key] = list[num]
        num += 1
    return d

The problem is that whenever the loop returns to this function it reads the same line! and i want the offset to drop a new line

TeviXor
  • 5
  • 1
  • 3
  • What is *"the offset"*? – Peter Wood May 02 '17 at 18:33
  • You read one line, then close the file. Read each line from the file [as the documentation says](https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files) and do what you want with it. – Peter Wood May 02 '17 at 18:34
  • can you show me how? – TeviXor May 02 '17 at 18:38
  • This isn't really a tutorial site. There is adequate documentation. Try something and ask a question if you get stuck. – Peter Wood May 02 '17 at 18:41
  • Take a look at [**`csv`**](https://docs.python.org/2/library/csv.html) particularly [**`DictReader`**](https://docs.python.org/2/library/csv.html#csv.DictReader). – Peter Wood May 02 '17 at 18:44

2 Answers2

0

The problem is that you're telling the program to only read the first line of the file every time you call the function at the file.readline() statement. You should read all the file in at once into a list, then loop through the lines that have been read into the list.

Example:

def load_from_file():
    with open("players.txt", "r") as myfile # open file for reading
       myfile = file.readlines()
    return myfile

def create_dictionary(line):
    d = {}
    list = line.split(",")
    prop = {"position":"","number":"","name":"","birth":"","id":""}
    keys = (sorted(prop))
    num = 0
    for key in keys:
       d[key] = list[num]
       num += 1
    return d

data = []
filedata = load_from_file()
for line in filedata:
    data.append(create_dictionary(line))

P.S. Not sure what all you're trying to do with data, but this should help you get the gist.

Jay Atkinson
  • 3,279
  • 2
  • 27
  • 41
  • @Peter Wood, not necessary but way less complicated particularly with the way he was open the file every time in the function. Easier to operate on Python lists instead of handling file pointers. – Jay Atkinson May 02 '17 at 18:42
  • `for line in myfile` isn't complicated – Peter Wood May 02 '17 at 18:46
0

Using DictReader from the csv module:

def load_from_file():
    with open("players.txt") as players:
        fields = ["birth", "id", "name", "number", "position"]
        reader = csv.DictReader(players, fields)
        return list(reader)
Peter Wood
  • 23,859
  • 5
  • 60
  • 99