How To Save File In Python

Saving a file is an essential operation when working with data, which makes reading and writing files one of the most important tasks in Python. In this tutorial, we’ll walkthrough the steps required to save a file in Python using different methods.

Step 1: Using the Built-in open() Function

The built-in open() function can be used to create or open a file. By default, the open() function will open the file in read mode, but we can use different modes to modify and save files as needed.

The different file opening modes are:

  1. r: Opens the file in read-only mode. This is the default mode if no mode is specified.
  2. w: Opens the file for writing. If the file doesn’t exist, it creates a new file. If the file already exists, it truncates the file to start with an empty file.
  3. a: Opens the file for appending. If the file doesn’t exist, it creates a new file. If the file exists, it moves the file pointer to the end of the file, so new data is written at the end.
  4. x: Opens the file for exclusive creation. If the file already exists, it raises an error.
  5. b: Opens the file in binary mode (used in combination with other modes, e.g., ‘rb’, ‘wb’).
  6. t: Opens the file in text mode (used in combination with other modes, e.g., ‘rt’, ‘wt’). This is the default mode if not specified.

Here’s an example of how you can save a file using the open() function:

The above code creates a new file named ‘sample.txt’ and writes two lines in it. The with statement ensures that the file is properly closed once the operation is completed.

Output content of ‘sample.txt’:

Hello, this is a sample text file.
This is another line in the file.

Step 2: Using the os Module

The os module in Python provides a way to work with the filesystem. We can use this module to rename, delete, or create files and directories.

Here’s an example of how to save a file using the os module:

This code snippet creates a new file named ‘sample_os.txt’ and writes a single line in it. The os.path.exists() function is used to check if the file already exists before creating it.

Output content of ‘sample_os.txt’:

Hello, this is a sample text file using the os module.

Full Code

Output content of ‘sample.txt’:

Hello, this is a sample text file.
This is another line in the file.

Output content of ‘sample_os.txt’:

Hello, this is a sample text file using the os module.

Conclusion

Saving files in Python is a very common task, and understanding how to use the built-in open() function and the os module is essential for handling files. In this tutorial, we covered two simple methods for saving files in Python with examples.

You can now easily create, modify, and save files using these methods.