我的程序有问题:
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/