File Operations in Python – Read and Write files with Python

File Operations in Python – Read and Write Files With Python

Python includes built-in functions for file manipulation, including file creation, writing, and reading. In Python, two distinct file types can be processed: regular text files and binary files, encoded using a sequence of binary digits (0s and 1s).

  • Text files: In this category of files, each line of text concludes with a designated character known as the End of Line (EOL) character. The default EOL character in Python is the newline character (‘n’).
  • Binary files: In contrast, binary files do not employ line terminators, and the data is stored in a format that can be understood by a computer, typically as a series of binary values.

Save $100 in the next
5:00 minutes?

Register Here

Why are File Operations in Python Needed?

When you deal with big data sets for machine learning, you’ll often need to handle files. Python is a popular language for data science, and it provides various ways to work with files.

Let’s take a look at some of these file operations in Python.

File Access Modes

Access modes in Python determine how you can use a file once it’s open. They dictate what you can do with the file and where to start reading or writing. Think of it like a cursor that shows where you are in the file. There are six access modes in Python:

Read Only (‘r’): This mode lets you open a text file for reading. The cursor starts at the beginning of the file. If the file doesn’t exist, it will give you an error. This is also the default mode when you open a file.

Read and Write (‘r+’): You can open the file for reading and writing. The cursor is at the start of the file. If the file doesn’t exist, it raises an error.
Write Only (‘w’): This mode allows you to open a file for writing. If the file already exists, it will clear its contents and overwrite them. The cursor starts at the beginning. If the file doesn’t exist, it creates one.

Write and Read (‘w+’): Similar to ‘w,’ this mode lets you read and write. It clears existing data, starts at the beginning, and creates a new file if it doesn’t exist.
Append Only (‘a’): Open the file for writing, but this time the cursor goes to the end of the file. If the file doesn’t exist, it creates one. Data you write add at the end without erasing existing content.

Append and Read (‘a+’): This mode is for reading and writing, just like ‘a’. It also puts the cursor at the end; if the file doesn’t exist, it creates it. New data will added after what’s already there.

Python File Reading

Example

f = open("test.txt", "r")
print(f.read())

Explanation

f = open(“test.txt”, “r”): In this line, a file name “test.txt” is open in read mode (‘r’). You can only read the file’s contents, not modify or write. The open() function returns a file object assigned to the variable f. This object represents the opened file and allows you to perform various operations.

print(f.read()): This line reads the entire content of the file represented by the f object using the read() method. The read() method reads the file from the cursor’s current position (initially at the beginning of the file) until the end. It then returns the content as a string. Finally, the print() function displays the file’s content on the console.

Python File Writing

Example

file_path = "example.txt"  # Replace with the path to your file
with open(file_path, 'w') as file:
    # Write data to the file
    file.write("Hello, World!n")
    file.write("This is a line of text.n")
    file.write("And this is another line of text.n")

Output

Hello, World!
This is a line of text.
And this is another line of text.

Explanation

We use the open() function to open a file named “example.txt” in write mode (‘w’). If the file doesn’t exist, it will be created. If it already exists, its contents will be overwritten. We use a statement to ensure the file is closed adequately after writing to it. This is a recommended practice as it automatically handles file closure and exception handling. We use the write() method to write data to the file. Each call to write() appends the specified data to the file. In this example, we’re writing three lines of text, including newline characters (n) to separate the lines.

Conclusion

Python offers robust built-in file manipulation functions, accommodating text and binary files. Understanding file access modes is crucial for effective file handling in Python, with options like read-only, read-write, write-only, and append modes. The examples illustrate the simplicity of file reading and writing operations, showcasing Python’s versatility in managing files for various data processing tasks.

Save $100 in the next
5:00 minutes?

Register Here