Answer the question
In order to leave comments, you need to log in
How to output the entire contents of an array to a file?
There is such a code in python, I wanted to display all the contents in the console, but the text does not fit there, so I had to write the contents to a file. But only the last element of the list is written to the file, and you need to output all 121. How to do this? I will be very grateful
i = 0
while(i <= 121):
val = "elif call.data == \"f{0}\": \n \
FILTER[user_id] = '{1}' \n \
msg = bot.send_message(call.message.chat.id, \"Выбран стиль {0}.\") \n \
bot.register_next_step_handler(msg, load) \n \
bot.edit_message_reply_markup(call.message.chat.id, call.message.message_id, reply_markup = None) \n \
".format(i, list[i+1])
f1 = open("D:/text1.txt", 'w')
f1.write(val)
i += 1
Answer the question
In order to leave comments, you need to log in
You are overwriting the file each time by passing the 'w' argument. Of course there will be only the last line
f1 = open("D:/text1.txt", 'w')
s = 'elif call.data == "f{0}": \n \
FILTER[user_id] = \'{1}\' \n \
msg = bot.send_message(call.message.chat.id, "Выбран стиль {0}.") \n \
bot.register_next_step_handler(msg, load) \n \
bot.edit_message_reply_markup(call.message.chat.id, call.message.message_id, reply_markup = None) \n \
'
with open('D:/text1.txt', 'a') as f:
for i, value in enumerate(list[1:]):
f.write(s.format(i, value))
Opening a file for every line is a very costly operation. Not to mention that you do not even close it, which will potentially lead to underwriting. Correctly work with files through context managers:
i = 0
with open("D:/text1.txt", "w") as f1:
while i <= 121:
val = 'elif call.data == "f{0}": \n \
FILTER[user_id] = \'{1}\' \n \
msg = bot.send_message(call.message.chat.id, "Выбран стиль {0}.") \n \
bot.register_next_step_handler(msg, load) \n \
bot.edit_message_reply_markup(call.message.chat.id, call.message.message_id, reply_markup = None) \n \
'.format(
i, list[i + 1]
)
f1.write(val)
i += 1
instead of w in open put a
in this case w overwrites the file. a -- flag for adding content.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question