Home python Writing a list to a txt file in python

Writing a list to a txt file in python




Actually, how to write the result of the function to a txt file?

f = open ('***. txt', 'w')
f.write ('??????')
f.close ()

Answer 1, authority 100%

There are several options:

f.write ("\ n" .join (list) .join ("\ n"));

for item in list:
  f.write ("% s \ n"% item)

import pickle
# Good for non-string lists as we will do serialization
# using pickle. Can be serialized to json or xml for example.
pickle.dump (list, f)

Answer 2, authority 73%

To write a space-separated text representation of list items to a file in Python 3:

with open ("file.txt", "w") as file:
  print (* list, file = file)

See What do * (asterisk) and ** double asterisk mean in Python?

If you want to print each element on its own line:

print (* list, file = file, sep = "\ n")

You can format it with your hands (the same result):

print ("\ n" .join (map (str, list)), file = file)

Or print one element at a time (same result):

for item in list:
  print (item, file = file)

To save in JSON format:

import json
with open ("list.json", "w", encoding = "utf-8") as file:
  json.dump (list, file)

To save as csv:

import csv
with open ("list.csv", "w", newline = '') as file:
  csv.writer (file) .writerow (list)

The code continues to work even if the elements contain commas, quotes, newlines inside.

Answer 3, authority 18%

with open ('text.txt', 'w') as txt_file:
  txt_file.write (text)

text – result of function execution

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions