SirGoose
SirGoose

Reputation: 129

Python: Creating a list from a file

So I'm trying to create a function that will open a text file, read it line by line, then take the data it pulls from it to create a list.

def file_open():
    filename = str(input("enter file name for perk.py to sort through"))
    fob = open(str(filename), 'r')
    theList = []
    for line in fob:
        if not line:
            break
        x = fob.readline()
        x = int(x)
        theList.append(x)
    print("List =", theList)
    return theList

Here is the text file that I'm pulling data from:

9
7
1
3
2
5
4

My expected output should be:

List =[9,7,1,3,2,5,4]

However when I run this function I get the following error:

Traceback (most recent call last):
File "H:/CSCI-141/Week 7 Work/perk.py", line 47, in <module>
  main()
File "H:/CSCI-141/Week 7 Work/perk.py", line 44, in main
  perk_sort(file_open())
File "H:/CSCI-141/Week 7 Work/perk.py", line 17, in file_open
  x = int(x)
ValueError: invalid literal for int() with base 10: ''

I would really appreciate it if someone could tell me why I'm getting this error and how to fix my code, thank you!

Upvotes: 1

Views: 163

Answers (1)

Andr&#233; Teixeira
Andr&#233; Teixeira

Reputation: 2562

You are probably trying to apply int() on a empty line. You can get all lines with file.readlines() and then iterate over them easily.

Try this:

def file_open():
    filename = "PATH TO YOUR FILE"
    fob = open(filename, 'r')
    lines = fob.readlines()

    final_list = []
    for line in lines:
        final_list.append(int(line))

    print "List: %s" % final_list

Upvotes: 1

Related Questions