1

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!

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

I tried that, however it returns ['9\n', '7\n', '1\n', '3\n', '2\n', '5\n', '4\n']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.