0% found this document useful (0 votes)
5 views22 pages

Python Unit4 byMultiAtoms

The document provides an overview of Python file operations, detailing how to read, write, and manipulate files using built-in functions. It covers various file modes, methods for reading and writing data, and best practices for file handling, including the use of context managers. Additionally, it introduces the seek() and tell() functions for managing file pointers and emphasizes the importance of proper file management.

Uploaded by

astpanday
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views22 pages

Python Unit4 byMultiAtoms

The document provides an overview of Python file operations, detailing how to read, write, and manipulate files using built-in functions. It covers various file modes, methods for reading and writing data, and best practices for file handling, including the use of context managers. Additionally, it introduces the seek() and tell() functions for managing file pointers and emphasizes the importance of proper file management.

Uploaded by

astpanday
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Multi Atoms Plus

Python Programming

Unit-4 One Shot (BCC-302 & BCC-402)

Python File Operations


Multi Atoms Plus
Unit-4 Syllabus

Theory + Coding Part + Important Ques


Multi Atoms Plus
Introduction to Python File Operations
File operations in Python allow you to perform various tasks on files such as reading,
writing, appending, and manipulating the file pointer. Python provides built-in
functions and methods to work with files efficiently.

File: A file is a digital container used to store data on a computer. It has a name, often
with an extension indicating its type (e.g., .txt for text files), and can contain various
types of information such as text, images, or programs. Files are essential for data
allowing information to be saved and retrieved later.

Types of files:

1. Text Files : .txt, .log etc.


2. Binary Files : .mp4, .mov, .png etc.
Multi Atoms Plus
File operations in Python involve several key tasks. You can open a file in various
modes such as read ('r'), write ('w'), and append ('a'). Reading operations include
reading the entire file content at once, reading line by line, or reading all lines into a
list. Writing operations allow you to write a single string or multiple lines to a file.

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

Open the File → Perform Operation → Close the File


open() read() or write() close()
Multi Atoms Plus
File Opening in Python
File opening in Python involves using the open() function, which allows you to access
and interact with files.

file = open(filename, mode)


filename: Specifies the name of the file you want to open, including its path if it's not
in the current directory.
mode: Specifies the mode in which the file is opened.
# Opening a file in read mode
file = open('example.txt', 'r')
Multi Atoms Plus
Different Modes
● 'r': Read mode. Opens a file for reading. (default mode)
● 'w': Write mode . Opens a file for writing. If the file exists, it truncates the file to
zero length. If the file does not exist, it creates a new file.
● 'a': Append mode. Opens a file for appending data. The file pointer is at the end
of the file if the file exists. If the file does not exist, it creates a new file for writing.
● 'b': Binary mode. This can be added to any of the above modes (e.g., 'rb', 'wb', 'ab')
to work with binary files.
● '+': Open a file for updating (reading and writing). (eg. r+, w+)
It's recommended to use the with statement when opening files. This ensures that the file is
properly closed after its suite finishes, even if an exception is raised.

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


Multi Atoms Plus
Reading files in Python
It involves several methods to retrieve data stored in files. The main methods for
reading files are:
● read()
● readline()
● readlines()
Reading the Entire File: The read() method reads the entire content of the file at once
and returns it as a single string. This is useful for small files but can be inefficient for
large files as it loads all data into memory.
file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()
Multi Atoms Plus
Reading Line by Line: The readline() method reads one line at a time from the file.
This is useful for processing large files line by line, as it doesn't load the entire file into
memory at once.

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


line = file.readline()
print(line)
file.close()
.strip() removes the newline character
print(line.strip())
Multi Atoms Plus
Reading All Lines: The readlines() method reads all lines of the file and returns them
as a list of strings, where each string is a line from the file. This method can be
convenient for iterating over lines but may be inefficient for very large files.
file = open('example.txt', 'r')
lines = file.readlines()
print(lines)
file.close()
o/p = ['fsfs\n', 'sfsfsfsf\n', 'sfsf']
.strip() removes the newline character
print(lines.strip())

Let’s Code..
Multi Atoms Plus
Writing to files in Python
It is an essential operation for data storage, logging, configuration files, and more. Here
are the basic methods for writing to files, including writing a single string, writing
multiple lines, and appending to a file.

1. Writing a Single String


The write() method allows you to write a single string to a file. This is useful for simple
text output. If the file does not exist, it will be created. If it does exist, the file will be
truncated (emptied) before writing the new content.

file = open('example.txt', 'w')

file.write('Hello, World!\n')

file.close()
Multi Atoms Plus
2. Writing Multiple Lines
The writelines() method allows you to write a list of strings to a file. Each string in the
list is written to the file sequentially. This method does not add new lines
automatically, so each string should end with a newline character if needed.

lines = ['First line\n', 'Second line\n', 'Third line\n']

file = open('example.txt', 'w')

file.writelines(lines)

file.close()
Multi Atoms Plus
3. Appending to a File
To append data to an existing file without truncating it, you can open the file in
append mode ('a'). The new data will be added at the end of the file.

file = open('example.txt', 'a')

file.write('This line will be appended.\n')

file.close()

By using these methods, you can efficiently write data to files in Python, ensuring
proper file management and data persistence. Always remember to close the file after
writing to ensure that all data is flushed from the buffer and saved to the disk, and to
release system resources.

Let’s Code..
Multi Atoms Plus
`r'' Open text file for reading. The stream is positioned at the beginning of the file.

`r+'' Open for reading + writing. The stream is positioned at the beginning of the file.

`w'' Truncate file to zero length or create text file for writing. The stream →beginning.

`w+'' Open for reading + writing. The file is created if it does not exist, otherwise it is
truncated. The stream → beginning of the file.

`a'' Open for writing. The file is created if it does not exist. The stream is positioned at
the end of the file. Subsequent writes to the file will always end up at the then current
end of file.

`a+'' Open for reading + writing. The file is created if it does not exist. The stream is
positioned at the end of the file.

Let’s Code..
Multi Atoms Plus
Deleting the file in Python
To delete a file in Python, you can use the os.remove() function from the os module.
Here’s how you can delete a file:

import os
file_path = 'example.txt'
if os.path.exists(file_path):
os.remove(file_path)
print(f"{file_path} successfully deleted.")
else:
print(f"{file_path} does not exist.")
Let’s Code..
Multi Atoms Plus
Q. WAPP to write the no. of letters and digits in the given input
String in a file object.
input_string = input("Enter a string: ") # Write counts to a file
letters_count = 0 file_path = 'letter_digit_counts.txt'
digits_count = 0 file = open(file_path, 'w')
file.write(f"Number of letters:
{letters_count}\n")
for char in input_string:
file.write(f"Number of digits: {digits_count}\n")
if char.isalpha():
file.close()
letters_count += 1
elif char.isdigit():
digits_count += 1
Let’s Code..
Multi Atoms Plus
File Handler in Python
File Handler Basics:

● A file handler, or file object, is an interface to interact with files in Python


programs.
● It is created when a file is opened using the open() function.

Operations:

● Reading: Use methods like read(), readline(), or iterate over lines with a loop.
● Writing: Employ write() to add content to a file, or writelines() to write multiple
lines at once.
● Moving the Pointer: Adjust the file pointer with seek() to navigate through the
file.
● Querying Position: Determine the current position with tell().
Multi Atoms Plus
Modes: as previous

Closing Files:

● Call close() on the file handler to free up resources once operations are done.

Error Handling:

● Handle potential errors like FileNotFoundError or IOError when opening or


manipulating files.

Best Practices:

● Always close files after use to prevent resource leaks.


● Utilize context managers (with statement) for cleaner and safer file handling.
● Handle exceptions to gracefully manage file-related errors.
Multi Atoms Plus
seek() Function in Python
It is used to change the current position (or offset) of the file pointer within a file. This
function is particularly useful when you need to navigate to a specific location in a file
to read or write data.

file_object.seek(offset, whence)
offset: It specifies the number of bytes to move the file pointer.

whence: It specifies the reference point from where the offset is calculated. It can take
one of the following values:

● 0 (default): Start of the file


● 1: Current position of the file pointer
● 2: End of the file
Multi Atoms Plus
Moving the File Pointer:

● When you open a file, the file pointer starts at the beginning (0 offset).
● seek(offset, 0) moves the pointer offset bytes from the beginning of the file.
● seek(offset, 1) moves the pointer offset bytes from the current position.
● seek(offset, 2) moves the pointer offset bytes from the end of the file (a negative
offset is usually used in this case).
# Open a file Multi Atoms Plus
file = open('example.txt', 'r')
# Move pointer to the 10th byte from the start
file.seek(10, 0)
print(file.read(5)) # Reads 5 bytes from the current position (10th byte)
# Move 5 bytes forward from the current position
file.seek(5, 1)
print(file.read(10)) # Reads 10 bytes from the current position (15th byte)
# Move to the 10 bytes before the end of the file
file.seek(-10, 2)
print(file.read(5)) # Reads 5 bytes from this position (10 bytes before the end)
# Close the file
file.close()
Multi Atoms Plus
tell() function in Python
The tell() function returns an integer that represents the current position of the file
pointer in bytes from the beginning of the file.’

file_object.tell()

Understanding and utilizing tell() allows precise control over file operations,
especially when dealing with large files or when needing to track and manage
file positions dynamically during file processing in Python.

Let’s Code..
Multi Atoms Plus

Thanks for Watching


Please Subscribe and Share Multi Atoms Plus
Join Telegram for Notes

You might also like