我写了一个列出列表的程序
但是当导入文件的内容很高时
程序已关闭(崩溃)
这是我写的代码
在这张照片中,使用了内容较少的文件
这张照片使用的文件内容很多
def btn_start():
try:
if open_file1_text and open_file2_text :
file_1 = open(open_file1_text.get(), 'r')
file_2 = open(open_file2_text.get(), 'r')
lines_1 = file_1.readlines()
lines_2 = file_2.readlines()
global text
text = ("")
demo_text_box.delete(1.0,'end')
demo_text_box_a.delete(1.0,'end')
demo_text_box_a.insert(INSERT,start_text_demo )
for pline in lines_2:
for uline in lines_1:
demo_text_box.insert(INSERT,uline.rstrip('\n') + separator_text_.get() + pline)
text += (uline.rstrip('\n') + separator_text_.get() + pline)
file_1.close()
file_2.close()
except FileNotFoundError :
demo_text_box.delete(1.0,'end')
demo_text_box_a.delete(1.0,'end')
demo_text_box_a.insert(INSERT,File_Not_Found_Error )
答案 0 :(得分:0)
您的代码还有另一个问题:如果未找到file_2
,则file_1
将保持打开状态,这可能很糟糕(您想在不再需要它们时立即关闭文件)。
您可以使用with
语句解决此问题,即使出现异常,该语句也会自动关闭文件。
关于您的内存问题,我猜text
不能容纳在内存中,因此您可能希望将其内容写入另一个文件。
def btn_start(open_file1_text, open_file2_text):
if not (open_file1_text and open_file2_text):
return
try:
with open(open_file1_text.get(), 'r') as file_1:
lines_1 = file_1.readlines()
with open(open_file1_text.get(), 'r') as file_2:
lines_2 = file_2.readlines()
demo_text_box.delete(1.0, 'end')
demo_text_box_a.delete(1.0, 'end')
demo_text_box_a.insert(INSERT, start_text_demo)
with open('text.txt', 'w') as text_file:
for pline in lines_2:
for uline in lines_1:
demo_text_box.insert(INSERT,uline.rstrip('\n') + separator_text_.get() + pline)
text_file.write(uline.rstrip('\n') + separator_text_.get() + pline)
except FileNotFoundError :
demo_text_box.delete(1.0,'end')
demo_text_box_a.delete(1.0,'end')
demo_text_box_a.insert(INSERT,File_Not_Found_Error )
如果文件本身不适合存储(意味着您无法调用file.readlines()
),
您还可以在循环的每次迭代中阅读它们:
with open('text.txt', 'w') as text_file:
with open(open_file1_text.get(), 'r') as file_2:
for pline in file_2:
with open(open_file1_text.get(), 'r') as file_1:
for uline in file_1:
demo_text_box.insert(INSERT,uline.rstrip('\n') + separator_text_.get() + pline)
text_file.write(uline.rstrip('\n') + separator_text_.get() + pline)