Python:从文件创建列表 [英] Python: Creating a list from a file

查看:62
本文介绍了Python:从文件创建列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在尝试创建一个函数,该函数将打开一个文本文件,逐行读取它,然后获取从文本文件中提取的数据以创建一个列表.

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

我的预期输出应该是:

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!

推荐答案

您可能正在尝试将int()应用于空行. 您可以使用file.readlines()获取所有行,然后轻松地对其进行迭代.

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.

尝试一下:

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

这篇关于Python:从文件创建列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆