How To Create A Folder And Save Files In It Python

Working with folders and files is a common task in almost all programming languages. In Python, you can easily create a folder and save files in it using the built-in os module. In this tutorial, we will guide you through the process of creating a folder, checking its existence, and saving files within it.

Step 1: Importing Necessary Modules

To create folders and handle files, you need to import the os module. Here’s how to import the required module in your Python script:

Step 2: Setting up the Folder Path

Before creating a folder, you need to define its path. For example, let’s say you want to create a folder named “example_folder” in the same directory as your Python script. You can set up the folder path like this:

This code creates a folder path consisting of the script’s current directory and the folder_name.

Step 3: Creating the Folder

Now that the folder path is defined, let’s create the folder. You can use os.makedirs(folder_path) function to create the folder using the folder_path created earlier. But, to avoid FileExistsError, first check if the folder already exists using os.path.exists(folder_path):

Step 4: Saving a File in the Folder

To save a file in the newly created directory, you need to define its path and write data into it. Let’s say you want to create a text file named “sample.txt” and write “This is a sample text!” into it:

This code creates the file path by joining the folder_path with the file_name, and the “with” statement ensures the file is properly closed after writing the content.

Complete Code

Here is the full code for creating a folder and saving a file in it:

Output

Here is the expected outcome when you execute the script above:

Folder "example_folder" is created in the current working directory, containing the "sample.txt" file with the text "This is a sample text!".

Conclusion

In this tutorial, you’ve learned how to create a folder and save files in it using Python. This is a fundamental skill that every Python developer should be familiar with since working with directories and files is essential in many programming tasks. The os module and its functions, as demonstrated above, make handling folders and files a breeze.