0% found this document useful (0 votes)
20 views7 pages

Cse Material 4

The document discusses various file access modes in Python including: 1) Read mode ('r') which allows reading a file but not modifying it. If the file does not exist, an error is raised. 2) Write mode ('w') which overwrites an existing file or creates a new file if it does not exist. 3) Append mode ('a') which appends data to the end of a file, creating it if it does not exist. 4) Additional modes like 'r+', 'w+', 'a+', 'x' which allow both reading and writing, positioning the file pointer differently depending on the mode. The document provides examples of opening and reading/writing to

Uploaded by

aasthaa1805
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)
20 views7 pages

Cse Material 4

The document discusses various file access modes in Python including: 1) Read mode ('r') which allows reading a file but not modifying it. If the file does not exist, an error is raised. 2) Write mode ('w') which overwrites an existing file or creates a new file if it does not exist. 3) Append mode ('a') which appends data to the end of a file, creating it if it does not exist. 4) Additional modes like 'r+', 'w+', 'a+', 'x' which allow both reading and writing, positioning the file pointer differently depending on the mode. The document provides examples of opening and reading/writing to

Uploaded by

aasthaa1805
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/ 7

The open() Function – Access Modes

In [1]: path=r'C:\Users\dr19m\Desktop\practice program\notebook_prg\file_handling_io'


file_name=r'example_file.txt'
full_name="\\".join([path,file_name])
print(full_name)

C:\Users\dr19m\Desktop\practice program\notebook_prg\file_handling_io\example_file.t
xt

In [2]: path=r'C:\Users\dr19m\Desktop\practice program\notebook_prg\file_handling_io'


file_name=r'example_file.txt'
full_name=path+'\\'+file_name
print(full_name)

C:\Users\dr19m\Desktop\practice program\notebook_prg\file_handling_io\example_file.t
xt

In [3]: #Read Mode ('r'):


'''This is the default mode. It allows you to only read the file and not modify it.
If the file does not exist, an error will be raised.'''
######################################
fhand=open(full_name, 'r')
content=fhand.read()
print(content)
fhand.close()

The os.path.split(path) Method: This method accepts a file path and returns its dire
ctory name as well as the . So it is equivalent to using two separate methods os.pat
h.dirname() and os.path.basename()
The os.path.getsize(path) Method: This method returns the size of the file specified
in the path argument.
The os.listdir(path) Method: The method returns a list of filenames in the specified
path.

In [4]: #Write Mode ('w'):


'''This mode is used to write to a file. If the file already exists, it will
overwrite it. If the file does not exist, a new file will be created.'''
#########################################
file = open('example_write.txt', 'w')
#file.write('''Python's syntax emphasizes code readability and clarity, using inden
#define code blocks, reducing the need for explicit braces or keywords.''')
file.write('\nThis is another line.')
# You can also use the print function to write to a file
print('\nYet another line.', file=file)
file.close()
###to read you need to open file again in read mode.

In [5]: #Append Mode ('a'):


'''This mode is used to append data to the end of the file.
If the file does not exist, a new file will be created.'''
#############################################
file = open('example_append.txt', 'a')
file.write("\nPython's syntax emphasizes code readability and clarity.")
file.write('Appending another line.\n')
# Using print to append content
print('Yet another appended line.', file=file)
file.close()
###to read you need to open file again in read mode.
file=open('example_append.txt','r')
data=file.read()
print(data)
file.close()

Python's syntax emphasizes code readability and clarity.Appending another line.


Yet another appended line.

In [6]: #Write and Read Mode ('w+'):


'''This mode allows both reading and writing,
If the file already exists, it will overwrite it,
and if the file does not exist, a new file will be created.'''
#######################################################
file = open('example_w+.txt', 'w+')
# Write content to the file
file.write('This line is written in w+ mode.\n')
file.write('Adding another line.\n')
print('Pointer location after write operation:',file.tell())
# Move the file pointer to the beginning
print('Need to reset the pointer to read from the start')
file.seek(0,0)
# Read the content from the beginning
read_content = file.read()
print("Content read from the file:")
print(read_content)
print('Pointer location after read operation:',file.tell())
# Move the file pointer
# Write additional content at the end
#file.seek(0,2)
file.write('Appending more content at the end.\n')

# Move the file pointer to the beginning again


file.seek(0)

# Read the updated content


updated_content = file.read()
print("\nUpdated Content:")
print(updated_content)
file.close()
Pointer location after write operation: 56
Need to reset the pointer to read from the start
Content read from the file:
This line is written in w+ mode.
Adding another line.

Pointer location after read operation: 56

Updated Content:
This line is written in w+ mode.
Adding another line.
Appending more content at the end.

In [7]: #Read and Write Mode ('r+'):


'''This mode allows both reading and writing.
The file pointer is placed at the beginning of the file.'''
####################################################
file = open('example_write.txt', 'r+')
content = file.read()
print("Existing Content:")
print(content)
# Move the file pointer to the beginning
#file.seek(0)

# Write new content to the file


file.write('New line added in r+ mode.\n')
file.write('Adding another line.\n')

# Move the file pointer in the beginning


file.seek(0)

# Read the updated content


updated_content = file.read()
print("\nUpdated Content:")
print(updated_content)
file.close()

Existing Content:

This is another line.


Yet another line.

Updated Content:

This is another line.


Yet another line.
New line added in r+ mode.
Adding another line.

In [8]: #Append and Read Mode ('a+'):


'''This mode allows both reading and writing.
If the file exists, the file pointer is positioned at the end of the file, and
new data is appended. If the file does not exist, a new file is created.'''
#################################################
file = open('example_write.txt', 'a+')
# Write content to the file
# Move the file pointer to the beginning
#file.seek(0)
###########
file.write('____This line is appended in a+ mode.\n')
file.write('Adding another line.\n')

# Move the file pointer to the beginning


file.seek(0)
# Read the content from the beginning
read_content = file.read()
print("Content read from the file:")
print(read_content)
file.close()

Content read from the file:

This is another line.


Yet another line.
New line added in r+ mode.
Adding another line.
____This line is appended in a+ mode.
Adding another line.

In [9]: #Exclusive Creation Mode ('x'):


'''This mode is used for exclusive creation, meaning it will fail if the file
already exists.'''
#########################################
file = open('example_x1.txt', 'x')
file.write('This is a new file created using exclusive creation mode.\n')
file.close()
##########
file = open('example_x1.txt', 'r')
content=file.read()
print(content)
file.close()

This is a new file created using exclusive creation mode.

In [10]: #More on file read/write


file = open('example_seek.txt', 'w+')
# Write content to the file
file.write('0123456789abcdef')
# Move the file pointer to the beginning (offset=0, whence=0)
file.seek(0, 0)
# Read the first 5 bytes
data = file.read(5)
print("Read from the beginning:", data)
print('pointer loc after fires read op:',file.tell())
#file.seek(5, 0)
data = file.read()
print("Read after seeking forward:", data)
#file.seek(8, 0)
print('Pointer location:', file.tell())
file.close()

Read from the beginning: 01234


pointer loc after fires read op: 5
Read after seeking forward: 56789abcdef
Pointer location: 16

Open file in binary mode

In [11]: # Open a file in write and read binary mode ('w+')


file = open('example_seek.txt', 'wb+')
# Write content to the file
file.write(b'0123456789abcdef')

# Move the file pointer to the beginning (offset=0, whence=0)


file.seek(0, 0)

# Read the first 5 bytes


data = file.read(5)
print("Read from the beginning:", data)

# Move the file pointer 5 bytes forward (offset=5, whence=1)


print('current location of pointer', file.tell())
file.seek(5, 1)
print(f'location of pointer after shift of {5}:{file.tell()}')
# Read the next 5 bytes
data = file.read(5)
print("Read after seeking forward:", data)

# Move the file pointer to the end (offset=0, whence=2)


file.seek(0, 2)

# Write more content at the end


file.write(b'ghijklmnopqrstuvwxyz')

# Move the file pointer 10 bytes backward from the end (offset=-10, whence=2)
file.seek(-2, 2)

# Read the last 10 bytes


data = file.read()
print("Read from the end after seeking backward:", data)
file.close()

Read from the beginning: b'01234'


current location of pointer 5
location of pointer after shift of 5:10
Read after seeking forward: b'abcde'
Read from the end after seeking backward: b'yz'

In [12]: #Binary Read Mode ('rb'):


'''This mode is used to read a file in binary mode.'''
#########################################
fhand = open('example_file.txt', 'rb')
content=fhand.read()
fhand.close()
print(content)

b'The os.path.split(path) Method: This method accepts a file path and returns its di
rectory name as well as the . So it is equivalent to using two separate methods os.p
ath.dirname() and os.path.basename() \r\nThe os.path.getsize(path) Method: This meth
od returns the size of the file specified in the path argument. \r\nThe os.listdir(p
ath) Method: The method returns a list of filenames in the specified path. \r\n'

In [13]: #Binary Write Mode ('wb'):


'''This mode is used to write to a file in binary mode.'''
##############
file = open('example_wb.txt', 'wb')
file.write(b'''Python's syntax emphasizes code readability and clarity, using
indentation to define code blocks''')
file.write(b'\nThis is another line.')
# You can also use the print function to write to a file
file.close()
file = open('example_wb.txt', 'rb')
print(file.tell())
data=file.read()
print(data)
file.close()

0
b"Python's syntax emphasizes code readability and clarity, using \nindentation to de
fine code blocks\nThis is another line."

In [14]: fhand = open('image_example.png', 'rb')


content=fhand.read()
fhand.close()
#print(content)

In [15]: # Open a smaller image file in binary write mode ('wb')


file= open('small_example.jpg', 'wb')
binary_data = bytes([
137, 80, 78, 71, 13, 10, 26, 10,
0, 0, 0, 13, 73, 72, 68, 82,
0, 0, 0, 2, 0, 0, 0, 2, 8, 6, 0, 0, 0, 29, 60, 147, 171,
0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130])
file.write(binary_data)
file.close()

In [16]: file= open('small_example.jpg', 'rb')


data=file.read()
print(data)
file.close()

b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x02\x00\x00\x00\x02\x08\x06\x00\x0
0\x00\x1d<\x93\xab\x00\x00\x00\x00IEND\xaeB`\x82'

with open(): It ensures that the file is properly closed after its suite finishes

In [17]: #The writelines() method is used to write a list of lines to a file.


#Each line in the list should be a string. Here's an example:
# Create a list of lines
lines_to_write = [
'This is the first line.\n',
'This is the second line.\n',
'And this is the third line.\n']

# Open a file in write mode


with open('example_writelines.txt', 'w') as file:
# Write the list of lines to the file
file.writelines(lines_to_write)

# Open the file in read mode to verify the content


with open('example_writelines.txt', 'r') as file:
# Read and print the content of the file
content = file.read()
print(content)

This is the first line.


This is the second line.
And this is the third line.

In [18]: ### opening a document file in binary mode


with open('syllabus.docx', 'rb') as file:
# Read and print the content of the file
content = file.read()
# print(content)

In [ ]:

You might also like