Python 文件读取和保存到数组
我的程序有问题:Python 文件读取和保存到数组,python,arrays,python-3.x,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(
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在任何情况下都不工作,但我看到问题发生在**标记行。它应该在第1代数组的“第一”索引处打印内容,对吗?但它打印:[]
对于if:它会抛出一个“索引超出范围”的错误。您的问题是,您首先打印行。之后,文件“在其末尾”,接下来就没有可以用第二个
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')
解决它。使用open(filename,“r”)作为文件的
会在您离开缩进时自动关闭文件对象,这是处理文件的首选方法:必须解决以下问题:
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')
不要调用变量list
,它与python内置的generation1[0]
冲突,打印generation1列表的第一个元素就足够了,至于错误“索引超出范围”,这意味着您的generation1
列表是空的,您正试图打印它的第一个元素可能list.seek(0)
在两个读取行之间
但效率极低。您应该只读取一次,然后将结果存储在变量中。我知道这很糟糕。我刚想到剧本会有效果