Python print list to file

Python Program to Write List to File

In this Python tutorial, we will discuss how to write list to file in Python using different examples.

There are five methods to write a list to file in Python, which are shown below:

  1. Using a for loop and the write() method
  2. Using the writelines() method
  3. Using the join() and the write() method
  4. Using the JSON module
  5. Using the pickle

How Python Write List to File

One common task is writing a list to a file, which can be useful for storing data that can be read later or for sharing data with other programs. There are several methods for writing a list to a file in Python, including using a for loop, the writelines () method, json module, etc.

Method-1: Python Write List to File using a for loop and the write() method

In this method, we use a for loop to iterate through each item in the list, and use the write() method to write each item to the file. We also add a newline character ‘\n’ after each item to write each item on a new line.

# create a list of numbers my_list = [1, 2, 3, 4, 5] # open a file named "output.txt" in write mode with open('output.txt', 'w') as f: # loop through the list and write each item to the file for item in my_list: f.write(str(item) + '\n') 

The code writes the elements of the list my_list to a file named output.txt, with each element on a new line. It uses the with statement to open the file in write mode and automatically close it after writing the data.

  • The for loop iterates over each element in the list and writes it to the file as a string, followed by a newline character to create a new line for the next element.
Читайте также:  Using JavaScript how to Create Captcha

Method-2: Python Write List to File using the writelines() method

In this method, we use the writelines() method to write each item in the list to the file.

# create a list of mobile phone brands mobile = ['samsung', 'redmi', 'oneplus'] # open a file named "f1.txt" in write mode file = open('f1.txt', 'w') # loop through the mobile phone list and write each item to the file for item in mobile: file.writelines([item]) # close the file file.close() 

The above code creates a list of mobile phone brands and then opens a file named “f1.txt” in write mode. It then loops through the list and writes each item to the file using the writelines() method. Finally, it closes the file.

Python write a list to file using the writelines method

Method-3: Python Write List to File using the join() and the write() method

In this method, we use the join() method to concatenate all the items in the list into a single string, separated by newline characters ‘\n’. We then use the write() method to write this string to the file.

# Define a list containing different types of values my_list = ["USA", 2, 3, 4, 5] # Open a file named 'join.txt' in write mode using a context manager # and write the contents of the list to the file in a specific format with open('join.txt', 'w') as f: f.write('\n'.join(map(str, my_list))) 

The above code defines a list called my_list containing various data types. It then uses the with a statement to open a new file called ‘join.txt’ in write mode and writes the contents of my_list to the file, with each element on a new line.

Method-4 Python Write List to File using the JSON module

In this method, we use the json module to write the list to a file in JSON format. We use the dump() method to write the list to the file in a JSON-encoded format.

# Import the json module, which provides an easy way to encode and decode JSON data import json # Define a list containing different types of values my_list = ["USA", 2, 3, 4, 5] # Open a file named 'output.json' in write mode using a context manager # and use the json.dump() function to write the contents of the list to the file in JSON format with open('output.json', 'w') as f: json.dump(my_list, f) 

The above code imports the json module, which provides functionality for working with JSON data. It defines a list called my_list containing various data types.

  • It then uses the with statement to open a new file called ‘output.json’ in write mode and writes the contents of the list to the file in JSON format using the json.dump() function.

Method-5: Python Write List to File using the pickle

In this method, we use the pickle module to write the list to a file in a binary format. We use the dump() method to write the list to the file in a binary-encoded format.

# Import the pickle module, which provides an easy way to serialize and deserialize Python objects import pickle # Define a list containing different types of values my_list = ["USA", 2, 3, 4, 5] # Open a file named 'output.pkl' in write mode using a context manager and binary mode 'wb' # and use the pickle.dump() function to write the contents of the list to the file in binary format with open('output.pkl', 'wb') as f: pickle.dump(my_list, f) 

The above code imports the pickle module, It defines a list called my_list containing various data types.

  • It then uses the with statement to open a new file called ‘output.pkl’ in write mode with binary mode ‘wb’, and writes the contents of the list to the file in binary format using the pickle.dump() function.

You may also like to read the following Python tutorials.

Conclusion

In this tutorial, we learned how to write python list to file using the different methods:

  • Using a for loop and the write() method
  • Using the writelines() method
  • Using the join() and the write() method
  • Using the JSON module
  • Using the pickle

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

3 Ways to Write a List to a File in Python

This quick tutorial demonstrates three methods to write a list to a file in Python scripting language.

In an earlier scripting tip, I showed you how to execute Shell commands in Python. In this quick tutorial, I’ll show you several ways for writing a list to a file in Python.

Writing a List to a File in Python

Actually the methods I am going to discuss here are used for writing text to a file in Python. The examples I am using here discusses writing the list to file but you can use it to write any kind of text. string etc using the functions mentioned here.

Method 1: Writing a list to a file line by line in Python using print

The print command in Python can be used to print the content of a list to a file. The list elements will be added in a new line in the output file.

Here’s a sample Python program for your reference:

MyList = ["New York", "London", "Paris", "New Delhi"] MyFile=open('output.txt','w') for element in MyList: print >>MyFile, element MyFile.close()

The file output.txt is opened in writing mode. The for loop in python iterates at each element in the list. The print commands write the element to the opened file.

New York London Paris New Delhi

As you can see, the list elements have been written line by line in the output file.

In the examples, the file has been opened in write mode with the ‘w’ option. All the previous content of the file in this mode will be overwritten.

If you want to save the previous content of the file, you can open the file in append mode by using the option ‘a’ instead of ‘w’.

Method 2: Write list to file in using Write function in Python

Now let’s see another way to save list to file in Python. We are going to use the Write() function.

The write() function takes string as the argument. So, we’ll be using the for loop again to iterate on each element in the list and write it to the file.

Here’s a sample Python program:

MyList = ["New York", "London", "Paris", "New Delhi"] MyFile=open('output.txt','w') for element in MyList: MyFile.write(element) MyFile.write('\n') MyFile.close()

Note that the elements in the list don’t have new line character. This is why I added the new line character ‘\n’ after each iteration so that the list elements are written to the file line by line. If you don’t do that you’ll see all the list content in one single line.

Method 3: Write all the lines to a file at once using writelines() function

The two other methods we saw wrote the content of the list to the file in line by line fashion. writelines() method is different. This method takes a list as input and writes the list as it is to the opened file.

MyList = ["New York", "London", "Paris", "New Delhi"] MyFile=open('output.txt','w') MyFile.writelines(MyList) MyFile.close()

If you use a command to view file in Linux command line, here’s what you’ll see in the output:

New YorkLondonParisNew Delhi

It’s not the prettiest output, I accept. But that’s the exact content of the list.

If you want to print line by line text to the file using writelines function, you can still do that but you’ll have to use extra effort.

What you can do here is that modify the list itself and add the newline character after each element. And now if you print the list using writelines(), you’ll have the output in line by line fashion.

Here’s the sample program for that:

MyList = ["New York", "London", "Paris", "New Delhi"] MyFile=open('output.txt','w') MyList=map(lambda x:x+'\n', MyList) MyFile.writelines(MyList) MyFile.close()

I hope this quick little tip helped you in writing a list to file using Python. If you use some other way, do share it with us. If the tutorial helped you, please let me know by leaving a comment below.

Источник

Оцените статью