文件读取并保存到阵列

时间:2018-01-11 17:51:38

标签: 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:它会引发一个错误,其中"索引超出范围"

2 个答案:

答案 0 :(得分:1)

您的问题是,您先打印线条。之后文件“在其末尾”没有更多的行可以用你的第二个readlines()读取,这就是生成[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

答案 1 :(得分:1)

必须解决问题:

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 fd:
        lines = fd.readlines()
    print(lines)
    print(lines[0])
    if generation1[0] == '#DOCTYPE_LIST!2.0\n':
        print('valid doc')
    else:
        print('unvalid doc')