Python: Creating a list from a file

前端 未结 1 835
时光取名叫无心
时光取名叫无心 2021-01-26 20:53

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():
             


        
相关标签:
1条回答
  • 2021-01-26 21:28

    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
    
    0 讨论(0)
提交回复
热议问题