Working with Files and Directories in Python

Table of Contents

  1. Introduction
  2. Creating and Opening Files
  3. Reading Files
  4. Writing Files
  5. Appending to Files
  6. Working with Directories
  7. Deleting Files and Directories
  8. Conclusion

Introduction

In Python, working with files and directories is an essential task for many applications. Whether it’s reading data from a file, writing information to a file, creating directories, or deleting files and directories, understanding how to manipulate files and directories is a fundamental skill for any Python programmer.

In this tutorial, you will learn how to perform various file and directory operations using Python. By the end of this tutorial, you will be able to:

  • Create and open files
  • Read data from files
  • Write data to files
  • Append data to files
  • Create and navigate directories
  • Delete files and directories

Before starting this tutorial, you should have a basic understanding of Python programming. It is also helpful to have Python installed on your machine.

Creating and Opening Files

To create or open a file in Python, you can use the built-in open() function. The open() function takes two parameters: the file path and the mode in which the file should be opened. The mode can be one of the following:

  • 'r': Read mode (default). Opens the file for reading.
  • 'w': Write mode. Opens the file for writing. If the file already exists, it is truncated. If the file does not exist, a new file is created.
  • 'a': Append mode. Opens the file for appending. New data will be written to the end of the file.
  • 'x': Exclusive creation mode. Creates a new file, but raises an error if the file already exists.
  • 'b': Binary mode. Opens the file in binary mode.
  • 't': Text mode (default). Opens the file in text mode.
  • '+': Update mode. Opens the file for updating (reading and writing).

Here’s an example that opens a file named “example.txt” in write mode: python file = open("example.txt", 'w') It is important to note that when you open a file using the open() function, you should always close it after you are done using it to free up system resources. You can close the file by calling the close() method on the file object: python file.close()

Reading Files

To read the contents of a file, you can use the read() method of the file object. The read() method returns the entire contents of the file as a single string.

Here’s an example that reads the contents of a file named “example.txt”: python file = open("example.txt", 'r') content = file.read() print(content) file.close() You can also read a file line by line using the readlines() method. The readlines() method returns a list of strings, where each string represents a line from the file.

Here’s an example that reads a file line by line: python file = open("example.txt", 'r') lines = file.readlines() for line in lines: print(line) file.close()

Writing Files

To write data to a file, you can use the write() method of the file object. The write() method takes a string as a parameter and writes it to the file.

Here’s an example that writes a string to a file named “example.txt”: python file = open("example.txt", 'w') file.write("Hello, world!") file.close() You can also use the writelines() method to write a list of strings to a file. Each string will be written as a separate line in the file. python file = open("example.txt", 'w') lines = ["Line 1", "Line 2", "Line 3"] file.writelines(lines) file.close()

Appending to Files

To append data to an existing file, you can open it in append mode ('a') using the open() function.

Here’s an example that appends a string to a file named “example.txt”: python file = open("example.txt", 'a') file.write("This line will be appended.") file.close()

Working with Directories

To create a directory in Python, you can use the mkdir() function from the os module. The mkdir() function takes the directory path as a parameter and creates a new directory.

Here’s an example that creates a new directory named “my_directory”: ```python import os

os.mkdir("my_directory")
``` To navigate through directories, you can use the `chdir()` function from the `os` module. The `chdir()` function takes the directory path as a parameter and changes the current working directory to the specified directory.
```python
import os

os.chdir("my_directory")
``` To get the current working directory, you can use the `getcwd()` function from the `os` module.
```python
import os

current_directory = os.getcwd()
print(current_directory)
``` ## Deleting Files and Directories

To delete a file in Python, you can use the remove() function from the os module. The remove() function takes the file path as a parameter and deletes the file.

Here’s an example that deletes a file named “example.txt”: ```python import os

os.remove("example.txt")
``` To delete an empty directory, you can use the `rmdir()` function from the `os` module. The `rmdir()` function takes the directory path as a parameter and removes the directory.
```python
import os

os.rmdir("my_directory")
``` To delete a directory and all its contents, you can use the `rmtree()` function from the `shutil` module. The `rmtree()` function takes the directory path as a parameter and removes the directory recursively.
```python
import shutil

shutil.rmtree("my_directory")
``` ## Conclusion

In this tutorial, you have learned how to work with files and directories in Python. You now know how to create and open files, read and write data to files, append data to files, create and navigate directories, and delete files and directories. This knowledge will be valuable for handling file-based operations in your Python projects.

Remember to always close files after you are done using them to free up system resources. Also, be cautious when deleting files and directories, as the actions cannot be undone.