cs file handeling
cs file handeling
Types of Files
In programming, handling files is a crucial aspect of data
manipulation and storage. Files can be categorized into various
types based on their content and structure. In this tutorial, we'll
explore different types of files such as text files, binary files, and
CSV files, along with understanding relative and absolute paths.
Types of Files
1. Text File
A text file contains human-readable characters encoded in a
specific format like ASCII or UTF-8. Text files are commonly
used for storing textual data, such as code, documents, or
configuration files.
2. Binary File
Binary files contain data encoded in binary format, which can
include images, videos, executables, etc. These files are not
human-readable and require specific programs to interpret their
contents correctly.
3. CSV File
CSV (Comma-Separated Values) files are a type of text file used
for tabular data storage. Each line in a CSV file represents a row,
and columns are separated by commas or other delimiters.
Paths
Relative Path
A relative path specifies the location of a file or directory
relative to the current working directory. It does not start from
the root directory.
Absolute Path
An absolute path specifies the complete location of a file or
directory starting from the root directory.
file.close()
In file handling with , the seek() and tell() methods are used
to manipulate and determine the current position of the file
pointer within a file.
seek() Method
The seek() method is used to move the file pointer to a
specified position within the file. It allows you to navigate to
different locations within the file for reading or writing
operations. The syntax for seek() method is:
file.seek(offset, whence)
tell() Method
The tell() method returns the current position of the file
pointer within the file. It provides the byte offset from the
beginning of the file to the current position. The syntax for
tell() method is:
file.tell()
Example:
Usage Scenario:
Let's consider a scenario where you have a large text file and
you want to read a specific portion of it. You can use seek() to
navigate to the desired position within the file efficiently
without reading unnecessary data from the beginning. Similarly,
tell() can be used to keep track of the current position of the
file pointer for further operations.
file_name = 'example.txt'
start_position = 10
end_position = 50
file_name = 'example.txt'
truncate_position = 20
truncate_file_at_position(file_name, truncate_position)
print("File truncated at position", truncate_position)
read_write_at_position(file_name, write_position,
write_data)
read_write_at_position(file_name, read_position)
Below is a program that reads a text file and displays all the
four-letter words present in the file. Each step is explained with
comments for better understanding:
def display_four_letter_words(file_name):
# Open the text file in read mode
with open(file_name, 'r') as file:
# Read the content of the file
content = file.read()
# Split the content into words based on
whitespace
words = content.split()
print("Four-letter words in the file:")
# Iterate through each word
for word in words:
# Check if the length of the word is 4
if len(word) == 4:
# Print the four-letter word
print(word)
# File name of the text file
file_name = 'example.txt'
file.close()
import pickle
Write/Create Operation
To write data to a binary file, you can use the write() method.
file.write(data)
Search Operation
To search for specific data within a binary file, you need to read
the file and then search for the desired data.
Append Operation
To append data to a binary file, you can use the seek() method
to move the file pointer to the end of the file and then use the
write() method to add data.
Update Operation
To update data in a binary file, you need to read the file, modify
the data, and then write the modified data back to the file.
# Read the file
file.seek(0)
content = file.read()
import csv
Opening and Closing a CSV File
You can use the open() function to open a CSV file in the
desired mode, and the file object can then be used with the
csv.reader() or csv.writer() functions.
import pickle
import pickle
# Open the binary file in read mode
with open('data.bin', 'rb') as file:
# Deserialize data from the binary file
data = pickle.load(file)
import pickle
import pickle
import pickle
import pickle
import pickle
# Define a class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
import pickle
# Data to be appended
new_person = Person('Charlie', 40)
import pickle
import pickle
import pickle
import pickle
import pickle
# Function to delete a specific data item from the
binary file
def delete_data(file_name, item_to_delete):
try:
# Open the binary file in read mode
with open(file_name, 'rb') as file:
# Deserialize data from the binary file
data = pickle.load(file)
except FileNotFoundError:
print("File not found.")
return
except EOFError:
print("File is empty.")
return
import csv
import csv
# Open the CSV file in read mode
with open('data.csv', 'r') as file:
# Create a CSV reader object
reader = csv.reader(file)
# Iterate over each row in the CSV file
for row in reader:
print(row)
import csv
import csv
# Open the CSV file in read mode
with open('data.csv', 'r') as file:
# Create a CSV reader object
reader = csv.reader(file)
# Read each row of data from the CSV file
for row in reader:
print(row)
import csv