python - 文件读取并保存到数组

标签 python arrays python-3.x

我的程序有问题:

def generate():
    list_path = filedialog.askopenfilename(title = "Open list from",filetypes = (("WSP list files","*.list"),("All files","*.*")))
    print('List opened for generation: '+list_path)
    list = open(list_path, "r")
    print(list.readlines())
    generation1 = list.readlines()
    **print(generation1[0])
    if generation1[0] == '#DOCTYPE_LIST!2.0\n':
        print('valid doc')
    else:
       print('unvalid doc')

if 在任何情况下都不起作用,但我发现问题发生在 ** 标记行。它应该打印 Generation1 数组的“第一个”索引处的内容,对吧?但它打印:[]

使用 if: 它会抛出“索引超出范围”的错误

最佳答案

你的问题是,你首先打印这些行。之后,文件“位于末尾”,后面不再有可以用第二个 readlines() 读取的行,这就是 Generation[0] 为空的原因。

def generate():
    list_path = filedialog.askopenfilename(title = "Open list from",filetypes = (("WSP list files","*.list"),("All files","*.*")))
    print('List opened for generation: '+list_path)
    with open(list_path, "r") as file:
        allLines = file.readlines()            # read all lines into a list
        print(allLines[0])                     # you can print from that list
    generation1 = allLines[:]           # or shallow copy the list of strings
    if generation1[0] == '#DOCTYPE_LIST!2.0\n':
        print('valid doc')      # and modify generation w/o touching allLines
    else:
       print('invalid doc')

解决了。 with open(filename,"r") as file: 当您留下缩进时,会自动关闭文件对象,这是处理文件的首选方式:reading-and-writing-files

关于python - 文件读取并保存到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48213126/

相关文章:

python - celery : understanding the big picture

python - 如何使用 boost 元组返回两个 vector

python-3.x - Tabula-py 用于无边框表格提取

python - 如何在python中不同的两个数组上应用不同的运算符

python-3.x - 分组重复项,允许 NaN 等于任何值

python - 在 Python 中调用具有正确参数的方法列表

python - 在有限域上插值多项式

c - 访问二维数组一行末尾的元素是 UB 吗?

python - numpy 数组转换规则不是 'safe'

c++ - C++中的std::vector与[]比较慢-为什么?