Day 6: File I/O in Python

·

5 min read

Python can be used to perform operations on a file (read and write data)

Types of all files

  1. Text files: .txt, .docx, .log etc (data is stored in character form)

  2. Binary Files: .mp4, .mov, .png, .jpeg etc

Basic operations on a file - Open, read and close file

Open, read and close a file

  • We have to open a file before reading or writing.
f = open("path_to_file_name", "mode")
  • If no mode is mentioned python by default assumes its a read mode

  • Let’s say we have a file “demo.txt” and another python file

HI everyone
How are you?
f = open("demo.txt", "r")
data = f.read()
print(data)
print(type(data))
f.close()

#output: 
#HI everyone

#How are you?
#<class 'str'>
  • It’s always a good practice to close the file after executing it.
ModeDescriptionBehavior
"r"ReadOpens the file for reading (default mode). File must exist, or it raises FileNotFoundError.
"w"WriteOpens the file for writing. Overwrites existing content or creates a new file if it doesn't exist.
"a"AppendOpens the file for writing. Adds content at the end without deleting existing data. Creates a new file if it doesn't exist.
"x"Exclusive CreationCreates a new file. Fails if the file already exists (raises FileExistsError).
"r+"Read & WriteOpens the file for both reading and writing. File must exist, or it raises FileNotFoundError.
"w+"Write & ReadOpens the file for both reading and writing. Overwrites existing content or creates a new file if it doesn't exist.
"a+"Append & ReadOpens the file for both reading and appending. Keeps existing content and allows reading. Creates a new file if it doesn't exist.
"rb"Read (Binary)Opens a file in binary mode for reading. File must exist.
"wb"Write (Binary)Opens a file in binary mode for writing. Overwrites existing content or creates a new file.
"ab"Append (Binary)Opens a file in binary mode for appending. Keeps existing content.
"xb"Exclusive Creation (Binary)Creates a new binary file. Fails if the file exists.
"rb+"Read & Write (Binary)Opens a binary file for both reading and writing. File must exist.
"wb+"Write & Read (Binary)Opens a binary file for both reading and writing. Overwrites content or creates a new file.
"ab+"Append & Read (Binary)Opens a binary file for both reading and appending. Creates a new file if it doesn't exist.

Reading a file

data = f.read() → reads entire file, the stream (cursor) reached the EOF after reading it

f = open("demo.txt", "r")
data = f.read()
print(data)
print(type(data))
f.close()

#output
#HI everyone

#How are you?
#<class 'str'>

f = open("demo.txt", "r")
data = f.read(7)
print(data)
f.close()

#output: HI ever

data = f.readline() → reads one line at a a time. After printing line1, extra new line will also be printed.

f = open("demo.txt", "r")
#data = f.read()
#print(data)
#print(type(data))
line1 = f.readline()
print(line1)
f.close()

#output:
#HI everyone
#new line here
f = open("demo.txt", "r")
line1 = f.readline()
print(line1)
line2 = f.readline()
print(line2)

#output:
HI everyone

How are you?

Let’s say if we already read the whole data of demo.txt file using f.read() and then use readline(), line1 and line2 will return empty space. It’s because after reading the file using read(), the cursor has reached the EOF and there’s noting to read for line1 and line2.

Empty next line will get printed once we try to print something after the cursor reaches EOF.
try to print line3 for below code, it will return empty new line.
#example
f = open("/Users/rishithapamisetty/Rishitha Python/demo.txt", "r")
data = f.read()
print(data)

line1 = f.readline()
print(line1)

line2 = f.readline()
print(line2)

f.close()
#output:
HI everyone
How are you?
#new line printed
#new line printed

Writing to a file

  • w - overwrite contents of file

  • a - append the data at the EOF

#Example1: 
f = open("demo.txt", "w")
f.write("I'm learning Python")
f.close()

#content in demo.txt file: (All the data in demo.txt is overwritten)
#I'm learning Python

#Example2:
f = open("demo.txt", "w")
f.write("I'm learning Python")
f.write("hello")
f.close()
#content in demo.txt file:
#I'm learning Pythonhello 

#Example3: (If I want to append data)
f = open("demo.txt", "a")
f.write("what is today's date")
f.close()
#content in demo.txt file:
#I'm learning Pythonhellowhat is today's date

#Example4: (to add data to new line)
f = open("demo.txt", "a")
f.write("\nWhat's the time now?")
f.close()
#content in demo.txt file:
#I'm learning Pythonhellowhat is today's date
#What's the time now?

with syntax

The “with” statement is used in file operations in Python because it provides a safe and efficient way to handle files. Here’s why you should use with when working with files:

  • Automatic File Closure: Ensures the file is closed properly after operations, even if an error occurs. Whoever we use “with”, we need not close the file, it gets closed automatically.

  • Prevents Resource Leaks: Frees system resources automatically, avoiding memory issues.

  • Exception Handling: Prevents file corruption by handling errors gracefully.

  • Encapsulation: Limits the file’s scope to the “with” block, preventing accidental modifications outside.

  • Better Performance: Ensures efficient handling of file operations, reducing risks of unintended behavior.

with open("demo.txt", "a") as f:
    data = f.read()
    print(data)

Deleting a file

  • We cannot simply delete the file using f.delete()

  • We have to use a module to delete the file. It’s done using os module.

  • In Python, you can delete a file using the os or pathlib module.]

Using os.remove()

  •     import os
        file_path = "example.txt"
    
        # Check if the file exists before deleting
        if os.path.exists(file_path):
            os.remove(file_path)
            print(f"{file_path} has been deleted.")
        else:
            print("The file does not exist.")
    

Using pathlib.Path.unlink()

from pathlib import Path
file_path = Path("example.txt")

# Check if the file exists before deleting
if file_path.exists():
    file_path.unlink()
    print(f"{file_path} has been deleted.")
else:
    print("The file does not exist.")
#WAF to find in which line of the file does the word "learning" occur first
def check_for_line():
    word = "learning"
    line_no = 1
    data = True
    with open("/Users/rishithapamisetty/Rishitha Python/practice.txt", "r") as f:
        while data:
            data = f.readline()
            if word in data:
                print(line_no)
                break
            else:
                line_no += 1
check_for_line()