Zone Of Makos

Menu icon

File Handling in Python

File handling is an essential part of programming in Python. It allows you to read and write data to and from files, which is necessary for many types of applications. In Python, you can use the built-in open() function to open and work with files.

Opening a File

To open a file in Python, you use the open() function, which takes two arguments: the name of the file to open, and the mode in which to open it. Here's an example:

    
file = open("myfile.txt", "r")
    
  

This code opens a file named "myfile.txt" in read mode ("r"). If the file doesn't exist, it will raise a FileNotFoundError exception.

Reading from a File

Once you have a file open, you can read data from it using various methods. The most basic method is read(), which reads the entire contents of the file as a string. Here's an example:

    
file = open("myfile.txt", "r")
data = file.read()
print(data)
file.close()
    
  

This code reads the entire contents of the file "myfile.txt" and prints it to the console. It then closes the file using the close() method to free up system resources.

Writing to a File

You can also write data to a file using the write() method. This method takes a string as an argument and writes it to the file. Here's an example:

    
file = open("myfile.txt", "w")
file.write("Hello, World!")
file.close()
    
  

This code opens the file "myfile.txt" in write mode ("w") and writes the string "Hello, World!" to it. If the file already exists, its contents will be overwritten.

Working with Binary Files

In addition to text files, Python can also work with binary files such as images and audio files. To open a binary file, you can use the "rb" (read binary) mode for reading, or the "wb" (write binary) mode for writing. Here's an example of reading a binary file:

    
file = open("myimage.jpg", "rb")
data = file.read()
file.close()
    
  

This code reads the entire contents of a binary file named "myimage.jpg" and stores it in the variable "data".

Conclusion

File handling is a crucial part of programming in Python, and the built-in open() function makes it easy to work with files in your code. By using the different modes of opening a file, you can read, write, and manipulate the contents of files in many ways. Whether you're working with text or binary files, Python provides a straightforward interface for accessing and manipulating file data. Remember to always close the file after you're done working with it, to avoid wasting system resources and potential issues with file locking. Happy coding!