Skip to main content
 首页 » 编程设计

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

2024年09月07日14小虾米

我的程序有问题:

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 数组的“第一个”索引处打印内容,对吧?但它打印:[]

如果:它会抛出“索引超出范围”的错误

请您参考如下方法:

你的问题是,你先打印了这些行。之后文件“在其末尾”,没有更多的行可以用你的第二个 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