Python

Write to file in Python

Write to file in Python. This code snippet constructs a file path, opens a file in write mode (creating it if it doesn't exist or overwriting it if it does), writes a string to the file, and prints a confirmation message upon completion. Files can be written as text or binary format. You can write to file provided text or string variable.

filewrite

Interactive recipe

You can use below interactive recipe to generate code. This recipe is available in MLJAR Studio.

In the below recipe, we assume that you have following variables available in your notebook:

  • content (type str)
  • other_content (type str)

Python code

# Python code will be here

Code explanation

  1. Construct file path from selected directory and file name. Please remember to add proper extension to file name.
  2. Open file in write mode, if file doesn't exist it will be created.
  3. Write a new content in the file. You can write provided text or string variable.

File can be written in text or binary format. Text format is human readable, whereas binary format is machine readable. Text files are prefered for small content. Please use binary format to store large data in the file.

« Previous
Read file