- Python print() to File
- Python Save Dictionary To File
- Table of contents
- How to save a dictionary to file in Python
- Example: save a dictionary to file
- Read Dictionary from a File
- Save a dictionary to a text file using the json module
- Save the dictionary to a CSV file
- About Vishal
- Related Tutorial Topics:
- Python Exercises and Quizzes
- Save Object to File in Python
- Use dill.dump() Function
- Further reading:
- Use pandas.to_pickle() Function
Python print() to File
Learn to use Python print() function to redirect the print output of a Python program or Python script to a file.
1. Print to File using file Argument
The print() function accepts 5 keyword arguments apart of the objects to print on the standard output (by default, the screen). One such keyword argument is file.
The default value of the file argument is sys.stdout which prints the output on the screen. We can specify any other output target which must be an object with write(string) method.
The given Python program opens the demo.txt in writing mode and write the test ‘Hello, Python !’ into the file.
sourceFile = open('demo.txt', 'w') print('Hello, Python!', file = sourceFile) sourceFile.close()
2. Redirecting Standard Output Stream to a File
Specifying the file parameter in all print() statements may not be desirable in some situations. We can temporarily redirect all the standard output streams to a file in this case.
Once all the required objects are written in the File, we can redirect the standard output back to the stdout .
import sys # Saving the reference of the standard output original_stdout = sys.stdout with open('demo.txt', 'w') as f: sys.stdout = f print('Hello, Python!') print('This message will be written to a file.') # Reset the standard output sys.stdout = original_stdout print('This message will be written to the screen.')
The program outputs to the file after setting the standard output to the file.
Hello, Python! This message will be written to a file.
The program again outputs to the console after resetting the standard putout target.
This message will be written to the screen.
3. Redirecting Script Output to File
Another way to redirect the output is directly from the command line while executing the Python script. We can use > character to output redirection.
The script output is in the file.
Python Save Dictionary To File
In this lesson, you’ll learn how to save a dictionary to a file in Python. Also, we’ll see how to read the same dictionary from a file.
In this lesson, you’ll learn how to:
- Use the pickle module to save the dictionary object to a file.
- Save the dictionary to a text file.
- Use the dump() method of a json module to write a dictionary in a json file.
- Write the dictionary to a CSV file.
Table of contents
How to save a dictionary to file in Python
Dictionaries are ordered collections of unique values stored in (Key-Value) pairs. The below steps show how to use the pickle module to save the dictionary to a file.
- Import pickle module The pickle module is used for serializing and de-serializing a Python object structure.
Pickling” is the process whereby a Python object is converted into a byte stream, and “unpickling” is the inverse operation whereby a byte stream (from a binary file) is converted back into an original object.
Example: save a dictionary to file
Let’s see the below example of how you can use the pickle module to save a dictionary to a person_data.pkl file.
import pickle # create a dictionary using <> person = print('Person dictionary') print(person) # save dictionary to person_data.pkl file with open('person_data.pkl', 'wb') as fp: pickle.dump(person, fp) print('dictionary saved successfully to file')
Person dictionary dictionary saved successfully to file
Read Dictionary from a File
Now read the same dictionary from a file using a pickle module’s load() method.
import pickle # Read dictionary pkl file with open('person_data.pkl', 'rb') as fp: person = pickle.load(fp) print('Person dictionary') print(person)
Save a dictionary to a text file using the json module
We can use the Python json module to write dictionary objects as text data into the file. This module provides methods to encode and decode data in JSON and text formats.
We will use the following two methods of a json module.
- The dump() method is used to write Python objects as JSON formatted data into a file.
- Using the load() method, we can read JSON data from text, JSON, or a binary file to a dictionary object.
Let’s see the below example of how you can use the json module to save a dictionary to a text file.
import json # assume you have the following dictionary person = print('Person dictionary') print(person) print("Started writing dictionary to a file") with open("person.txt", "w") as fp: json.dump(person, fp) # encode dict into JSON print("Done writing dict into .txt file")
Person dictionary Started writing dictionary to a file Done writing dict into .txt file
Note: You can also use the dump() method to write a dictionary in a json file. Only you need to change the file extension to json while writing it.
Read a dictionary from a text file.
Now, let’s see how to read the same dictionary from the file using the load() function.
import json # Open the file for reading with open("person.txt", "r") as fp: # Load the dictionary from the file person_dict = json.load(fp) # Print the contents of the dictionary print(person_dict)
Save the dictionary to a CSV file
The Python csv library provides functionality to read from and write to CSV files.
- Use the csv.DictReader() method to read CSV files into a dictionary.
- Use the csv.DictWriter() method to write a dictionary to a CSV file.
Example: Save the dictionary to a CSV file.
import csv # Dictionary to be saved person = print('Person dictionary') print(person) # Open a csv file for writing with open("person.csv", "w", newline="") as fp: # Create a writer object writer = csv.DictWriter(fp, fieldnames=person.keys()) # Write the header row writer.writeheader() # Write the data rows writer.writerow(person) print('Done writing dict to a csv file')
Person dictionary Done writing dict to a csv file
Example: Read a dictionary from a csv file
import csv # Open the csv file for reading with open("person.csv", "r") as infile: # Create a reader object reader = csv.DictReader(infile) # Iterate through the rows for row in reader: print(row)
OrderedDict([('name', 'Jessa'), ('country', 'USA'), ('telephone', '1178')])
Note: This will read the contents of the person.csv file and create a dictionary for each row in the file. You can then iterate through the rows and access the values in the dictionary using the column names as keys.
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter
Related Tutorial Topics:
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
- 15+ Topic-specific Exercises and Quizzes
- Each Exercise contains 10 questions
- Each Quiz contains 12-15 MCQ
Save Object to File in Python
Python’s pickle is a built-in module for serializing and de-serializing objects (data structures). It transforms an object into a sequence of bytes stored in memory or disk for later use in the same state.
We can save complete data structures such as lists, dictionaries, and custom classes. So, first, we imported the pickle module. Then we created a class Student() and an object std1 from it.
The with statement in Python is a control structure that simplifies code by handling exceptions and reducing the amount of code. It creates a context manager object responsible for managing the context block.
- Entering this context block requires opening a file or allocating memory.
- While exiting requires other activities like closing a file or deallocating memory.
We used the with statement to open the file using the open(file_name, ‘wb’) function that takes the filename and mode as arguments.
The pickle module provides the dump() function that converts a Python data structure into a byte stream format to write it to a binary file on the disk. For example, we used this method to convert std1 to binary stream format and wrote it to the file std1.pkl .
Use dill.dump() Function
Suppose we already have a Python library called dill installed. If we don’t have it, we can install it with pip install dill . To save an object to a file using the dill module:
- Use the open() function wrapped in the with statement to open the file.
- Use the dump.dill() function to save the object to the file.
Dill is an extension of Python’s pickle module, which we discussed while explaining the code snippet for using the pickle.dump() function. It stores complex data structures in an efficient format so different systems can use them in distributed applications such as web services.
It can also store multiple objects in a single file using its multi-pickling mode. We imported the module. Then, after successfully creating the object std1 from the class Student() , we used the with statement to open the file std1.pkl using the open() function.
The dump() method converts the object into binary format and saves them locally. It can create backups of important data or send data between two programs. For example, we used the dump() method to store the object std1 in the file std1.pkl .
Further reading:
Save Image to File in Python
Write Binary File in Python
Use pandas.to_pickle() Function
To save an object to a file using the pandas.to_pickle() function:
- Use the with context manager with the open() function to open the file.
- Use the pandas.to_pickle() function to store the object in a binary file.
Python’s pandas is an open-source module that provides high-performance data structures and analysis tools.
The primary purpose of this library is to provide efficient manipulation, filtering, reshaping, and merging operations on numerical tables or data frames. It aims to be the fundamental high-level building block for Python’s practical, real-world data analysis.
Once we created the object std1 from the class Student() , we opened the file std1.pkl using the built-in open() function wrapped in the with statement, which we discussed in the code section using the pickle.dump() function.
The pandas library provides a to_pickle() function that converts an object into a series of bytes and saves it in a file for future reference and use, enabling users to transfer data between applications.
It uses the pickle module internally, which simplifies the process by abstracting away the code necessary for properly serializing an object before writing it out to disk. For example, we used this method to write the std1 object to the file std1.pkl .
That’s all about how to save Object to File in Python.