Write Python List to a File

Write Python list to file

To write Python list to a file:

  • Open a file.
  • Separate the strings of the list by a new line (ironically, using join() method).
  • Add the result to a text file.

Here is how:

names = ["Alice", "Bob", "Charlie"]

with open("example.txt", mode="w") as file:
    file.write("\n".join(names))

As a result, you should see a text file with the names separated by a line break.

Alice
Bob
Charlie

Obviously, this is only one approach. If you are not satisfied with it, see the other examples below.

Write List to File As-Is

You cannot directly write a list to a file. But you can convert the list to a string, and then write it.

For example:

names = ["Alice", "Bob", "Charlie"]

with open("example.txt", mode="w") as file:
    file.write(str(names))

As a result, you see a text file called example.txt with the following contents:

['Alice', 'Bob', 'Charlie']

Write List to File Comma-Separated without Brackets

To write a list into a text file with comma-separated values without brackets, use string.join() method.

For example:

names = ["Alice", "Bob", "Charlie"]

with open("example.txt", mode="w") as file:
    file.write(", ".join(names))

As a result, you see a text file called example.txt with the following contents:

Alice, Bob, Charlie

Write Python List to File Tab-Delimited

names = ["Alice", "Bob", "Charlie"]

with open("example.txt", mode="w") as file:
    file.write("\t".join(names))

The result is a file called example.txt with the following contents tab-separated:

Alice	Bob	Charlie

Conclusion

Thanks for reading. I hope you enjoy it.

Happy coding!

Further Reading

How to Write to a File in Python

Switch Case in Python

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

Your email address will not be published.