File Reading and Writing Using Python: Easy Examples

Python offers a wide range of functionalities to deal with files, whether it’s reading from or writing to them. This tutorial will guide you through the process of file reading and writing in Python, using various code examples.

Table of Contents

Reading Files

Reading Text Files

You can read a text file in Python by opening it with the open function and then reading its content using the read method.

Use Sample file: titanic.csv

with open('file.txt', 'r') as file:
    content = file.read()
    print(content)

Here 'r' stands for read mode, and the with statement ensures that the file is closed after reading.

Reading Line by Line

You can also read a file line by line using a loop.

with open('file.txt', 'r') as file:
    for line in file:
        print(line)

Writing Files

Writing to Text Files

You can write to a text file by opening it in write mode ('w') and using the write method.

with open('file.txt', 'w') as file:
    file.write('Hello, World!')

This code will create a new file (or overwrite an existing one) with the text “Hello, World!”.

Appending to a File

If you want to add content to an existing file without overwriting it, you can use append mode ('a').

with open('file.txt', 'a') as file:
    file.write('Another line.')

Working with CSV Files

Python has a built-in csv module that simplifies working with CSV files.

Reading CSV Files

import csv

with open('file.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

Writing CSV Files

import csv

with open('file.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['Name', 'Age'])
    writer.writerow(['Alice', 30])
    writer.writerow(['Bob', 25])

File object methods

In Python, file objects provide several methods to work with files. Here’s a list of some of the main methods along with code examples to explain their usage:

1. open(): Opening Files

The open() function is used to open a file and returns a file object.

file = open('file.txt', 'r')

2. read(): Reading Files

The read() method reads the entire content of the file.

content = file.read()
print(content)

3. readline(): Reading a Line

The readline() method reads one line from the file.

line = file.readline()
print(line)

4. readlines(): Reading All Lines

The readlines() method reads all lines from the file and returns them as a list.

lines = file.readlines()
for line in lines:
    print(line)

5. write(): Writing to a File

The write() method writes a string to the file.

file = open('file.txt', 'w')
file.write('Hello, World!')

6. writelines(): Writing Multiple Lines

The writelines() method writes a list of strings to the file.

lines = ['Line 1', 'Line 2', 'Line 3']
file.writelines(lines)

7. seek(): Moving the Cursor

The seek() method moves the file cursor to a specific position.

file.seek(0)  # Move to the beginning of the file

8. tell(): Current Cursor Position

The tell() method returns the current position of the file cursor.

position = file.tell()
print(position)

9. close(): Closing a File

The close() method closes the file.

file.close()

10. flush(): Flushing the Internal Buffer

The flush() method flushes the internal buffer, meaning it writes any data in the buffer to the file without closing it.

file.flush()

Best Practice: Using with

It is good practice to use the with statement when working with files, as it ensures that the file is properly closed after its suite finishes.

with open('file.txt', 'r') as file:
    content = file.read()
    print(content)

These are some of the primary methods provided by file objects in Python to perform various file operations. They cover most of the basic needs for reading and writing files, allowing developers to easily manipulate file data.

Summary

Reading and writing files in Python is a straightforward process, thanks to the built-in functions and modules. Whether you’re dealing with text files or more complex formats like CSV, Python provides all the necessary tools to make file manipulation easy and efficient.

Tutorials