Skip to content

Python save data to file

  • by

To save data to a file in Python, you can use various methods depending on the type of data you want to save. Common methods include writing plain text data, JSON data, or binary data.

Python saves data to file example

Here’s a simple example of how to save data to a file in Python using each of the methods discussed earlier:

1. Saving Plain Text Data:

data_to_save = "Hello, this is some data to save to a file!"

# Open the file in write mode ('w' mode) and write the data to it
with open('output.txt', 'w') as file:
    file.write(data_to_save)

2. Saving Data as JSON:

import json

data_to_save = {
    "name": "John Doe",
    "age": 30,
    "email": "[email protected]"
}

# Open the file in write mode ('w' mode) and save the data as JSON
with open('output.json', 'w') as file:
    json.dump(data_to_save, file)

3. Saving Binary Data:

binary_data_to_save = b'\x00\x01\x02\x03\x04'  # Example binary data

# Open the file in write binary mode ('wb' mode) and save the binary data to it
with open('output.bin', 'wb') as file:
    file.write(binary_data_to_save)

Output:

Python save data to file

After running each of these code snippets, you will find three files created in the current working directory:

  1. output.txt: Contains the plain text data.
  2. output.json: Contains the JSON data in a structured format.
  3. output.bin: Contains the binary data.

You can open each file using a text editor or appropriate application for the file type to see the saved data. For instance, you can use a text editor to view the contents of output.txt and output.json, while binary files like output.bin might not be human-readable in a text editor.

Please make sure to adjust the file names and paths according to your specific use case. Also, remember to handle exceptions when working with file operations to handle potential errors gracefully.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading