In this article Files I/O in Python we give the information about Files I/O (Input/Output) in Python is used to read and write data to files. It allows us to perform tasks like opening, reading, writing, and closing files.

Files I/O in Python:

Files I/O: Text Files, Reading and Writing Files

Files I/O (Input/Output) in Python is used to read and write data to files. It allows us to perform tasks like opening, reading, writing, and closing files.

Text files in Python are used to permanently store and reuse data. Text files store only text data (such as letters, numbers, and special characters). Python has simple and useful functions available for reading and writing text files.

  1. Opening a File

The open() function is used in Python to open the file.

This function has two main parameters:

  1. File Name
  2. Mode

Modes:

mode description

r opens the file read-only. (default mode)

w Opens the file for writing. If the file already exists, it erases its data.

a Opens a file to add data to it.

Creates the x file only if it does not already exist.

r+ opens the file for reading and writing.

Example of opening a file:

# open the file

file = open(“example.txt”, “r”) # read only

print(file.read()) # Read the content of the file

file.close() # closing the file

  1. Writing to a File

Using w mode to write data to file:

# writing to file

file = open(“example.txt”, “w”) # Open the file for writing

file.write(“This is a new file.”) # Write the data

file.close() # close the file

Using a mode to add data:

# Adding data to the file

file = open(“example.txt”, “a”) # Open the file to add

file.write(“\nThis line is added later.”) # Add new line

file.close() # close the file

  1. Reading from a File

Use read() to read the entire file:

Use readline() to read line by line:

file = open(“example.txt”, “r”) # Open the file for reading

print(file.readline()) # Read the first line

print(file.readline()) # Read the second line

file.close() # close the file

Use readlines() to read all lines in a list:

file = open(“example.txt”, “r”) # Open the file for reading

lines = file.readlines() # Read all lines and store in a list

print(lines)

file.close() # close the file

  1. Using File with Context Manager (with Statement)

The with statement is used to automatically close the file.

Example:

# Use of Context Manager

with open(“example.txt”, “r”) as file:

    content = file.read()

    print(content)

# Here the file will be closed automatically.

  1. Some useful functions of file

Function Description

open(file, mode) is used to open the file.

read() reads the data of the entire file.

readline() reads a line from the file.

readlines() Converts all lines to a list.

write(data) writes data to the file.

close() is used to close the file.

seek(offset) Moves the cursor to a new position within the file.

tell() tells the current position of the cursor in the file.

  1. Binary Mode

If you need to read or write binary files (e.g. images, videos), you can use b mode:

  • rb: To read in binary mode.
  • wb: To write in binary mode.

Example:

# reading binary file

with open(“example.jpg”, “rb”) as file:

    binary_data = file.read()

    print(binary_data)

# writing binary file

with open(“new_image.jpg”, “wb”) as file:

    file.write(binary_data)

  1. Checking File Status

Example:

file = open(“example.txt”, “r”)

# cursor position in the file

print(“Cursor position:”, file.tell())

# Change cursor position after reading file

file.read(5)

print(“New position of cursor:”, file.tell())

# setting cursor to starting

file.seek(0)

print(“Reset cursor:”, file.tell())

file.close()

Some useful functions in text file

Function Description

open(file, mode) to open the file.

read() reads the complete data of the file.

readline() reads a line from the file.

readlines() reads all lines as a list.

write(data) writes data to the file.

writelines(list) writes all the elements of the list to a file.

close() to close the file.

seek(offset) sets the cursor to the new position.

tell() tells the current position of the cursor.

Error handling in text file

How to handle if file does not exist:

try:

    with open(“nonexistent.txt”, “r”) as file:

        content = file.read()

except FileNotFoundError:

    print(“File not found.”)

Deleting Text File

Usage of os module:

import os

if os.path.exists(“example.txt”):

    os.remove(“example.txt”) # Delete the file

    print(“File deleted.”)

otherwise:

    print(“The file does not exist.”)

conclusion:

With Files I/O in Python you can:

  • Can read text and binary data.
  • Can write or append data to a file.
  • Can manage files securely.

Introduction to GUI In Python:

GUI (Graphical User Interface) in Python is an interface that allows users to interact with the program in a visual and interactive way. Through a GUI you can use buttons, menus, text boxes, sliders, and other visual elements.

There are several toolkits available for creating GUIs in Python, such as:

  • Tkinter (default and most popular)
  • PyQt
  • Kivy
  • wxPython

Basic Concepts of GUI

  1. Widgets:

Every element used in a GUI like button, label, text box is called a “widget”.

  1. Events:

User actions such as button clicks, mouse movements, keyboard inputs are called events.

  1. Event Handling:

Teaching the program what to do at an event.

Using Tkinter to Create a GUI in Python

Tkinter is a GUI library already available with Python. It is easy and best suited for beginner use.

Basic structure of Tkinter program:

import tkinter as tk # Import Tkinter

# Create main window

root = tk.Tk()

# set window title

root.title(“My first GUI”)

# set window size

root.geometry(“400×300”)

# start the main loop

root.mainloop()

Some major widgets available in Tkinter

Widgets Description

Label to show text or information.

Button A clicking button.

Entry Text input box.

Text Multi-line text input.

Frame to group other widgets.

Canvas for graphics and drawings.

Listbox to show a list of options.

Scrollbar to scroll.

  1. Label and Button:

import tkinter as tk

def greet():

    label.config(text=”Hello, welcome to the Python GUI!”)

root = tk.Tk()

root.title(“Example of Label and Button”)

root.geometry(“300×200”)

# add label

label = tk.Label(root, text=”Text will appear here.”, font=(“Arial”, 14))

label.pack(pady=10)

# add button

button = tk.Button(root, text=”Click”, command=greet)

button.pack(pady=10)

root.mainloop()

  1. Text Input:

import tkinter as tk

def show_name():

    name = entry.get()

    label.config(text=f”Hello, {name}!”)

root = tk.Tk()

root.title(“Example of Entry”)

root.geometry(“300×200”)

# input box

entry = tk.Entry(root, font=(“Arial”, 14))

entry.pack(pady=10)

# button

button = tk.Button(root, text=”show name”, command=show_name)

button.pack(pady=10)

# label

label = tk.Label(root, text=””, font=(“Arial”, 14))

label.pack(pady=10)

root.mainloop()

3.Canvas:

import tkinter as tk

root = tk.Tk()

root.title(“Canvas example”)

root.geometry(“400×300”)

# create canvas

canvas = tk.Canvas(root, width=300, height=200, bg=”lightblue”)

canvas.pack()

# Draw shape on canvas

canvas.create_rectangle(50, 50, 150, 100, fill=”red”) # rectangle

canvas.create_oval(200, 50, 300, 150, fill=”green”) # circle

root.mainloop()

Event Handling:

In Python it is important to handle user actions through the GUI. This allows programs to take actions in response to events (such as clicks or keyboard inputs).

Example:

import tkinter as tk

def on_key(event):

    label.config(text=f”You pressed: {event.char}”)

root = tk.Tk()

root.title(“Example of Event Handling”)

root.geometry(“300×200”)

label = tk.Label(root, text=”Press any key.”, font=(“Arial”, 14))

label.pack(pady=50)

# keyboard event handling

root.bind(“<Key>”, on_key)

root.mainloop()

Some important Tkinter functions

function description

Tk() to create the main window.

mainloop() to keep the GUI running.

Label() to show text.

Button() to create a button.

Entry() for text input box.

pack() to add widgets to the window.

grid() to add widgets in grid format.

bind(event, callback) to handle an event.

GUI Library Options

  1. Tkinter:

For the simplest and beginner use.

  1. PyQt:

To create advanced GUI applications.

  1. Kivy:

For multi-touch and mobile applications.

  1. wxPython:

To create cross-platform GUI.

Conclusion:

Tkinter is the most simple and effective approach to GUI programming in Python. You can improve user experience and create interactive applications through GUI.

Some More: 

POP- Introduction to Programming Using ‘C’

DS – Data structure Using C

OOP – Object Oriented Programming 

Java Programming

DBMS – Database Management System

RDBMS – Relational Database Management System

Join Now: Data Warehousing and Data Mining 

Leave a Reply

Your email address will not be published. Required fields are marked *