10 - 2 Read Write Files
10 - 2 Read Write Files
•First, open a text file for reading by using the open() function
•Second, read text from the text file using the file read(), readline(), or readlines() method of
the file object.
•Third, close the file using the file close() method. This frees up resources and ensures
consistency across different python versions
open(<file>, <mode>)
Method Description
writeable() Returns whether the file can be written to or not
readable() Returns whether the file stream can be read or not
read() Returns the file content
readline() Returnsone line from the file
readlines() Returnsa list of lines from the file
write() Writes the specified string to the file
writelines() Write a list of strings to the file
close() Closes the file
flush() Flushes the internal buffer
seek() Change the file position
tell() Returnsthe current file
truncate() Resizes the file to a specified
Reading file
English,Charles Severance
English,Sue Blumenberg
English,Elloitt Hauser
Spanish,Fernando TardÃo Muñiz
authors.txt
r
English,Charles Severance
English,Sue Blumenberg
English,Elloitt Hauser
Spanish,Fernando TardÃo Muñiz
<class 'str'>
True
Another way to read a file
True
English,Charles Severance
English,Sue Blumenberg
English,Elloitt Hauser
Spanish,Fernando TardÃo Muñiz
English,Charles Seve
English,Ch
arles Severance
Engl
ish,Sue Blumenberg
English,Elloitt Hauser
Spanish,
English,Ch
arles Severance
Engl
read(n) function
•Reads atmost n bytes from the file if n is specified, else reads the entire file.
•Returns the retrieved bytes in the form of a string.
English,Charles Severance
English,Sue Blumenberg
English,Elloitt Hauser
Spanish,Fernando TardÃo Muñiz
English,Charles Severance
Engl
readline() function
Reads one line at a time from the file in the form of string
readlines() function
Reads all the lines from the file and returns a list of lines.
strip() function
Removes the leading and trailing spaces from the given string.
•First, open the text file for writing (or appending) using the open() function.
•Second, write to the text file using the write() or writelines() method.
•Third, close the file using the close() method.
Opens/create
a file File name
Variable / file handler Write mode
file = open(”names.txt”,”w”)
for x in range (4): Repeat the
process 4 times
name = input(”Enter name”)
Write inside the file file.write(name+”\n”)
file.close()
Asks user for a
name
Character Function
r Open file for reading only. Starts reading from beginning
of file. This default mode.
Open file for reading and writing. File pointer placed at\
r+ beginning of the file.
Appending files
Overright
Other modes
a+
fname = 'pcr_file.txt'
with open(fname, 'a+') as f:
f.write("From F. Lee Bailey\n")
Overright
From F. Lee Bailey
f.seek(0, 0)
"""
seek() function is used to change the position of the File Handle
to a given specific positi on.
File handle is like a cursor, which defines from where the data has to be read or written in
the file.
Syntax: f.seek(offset, from_what), where f is file pointer
Parameters:
Offset: Number of positions to move forward
from_what: It defines point of reference.
Returns: Return the new absolute position.
The reference point is selected by the from_what argument. It accepts three
values:
0: sets the reference point at the beginning of the file
1: sets the reference point at the current file position
2: sets the reference point at the end of the file
"""
print('\nSecond locati on: {}'.format(f.tell()))
content = f.read()
if not content:
print('Read nothing.')
else:
print(content)
print('Locati on aft er reading: {}'.format(f.tell()))
First location: 31
Read nothing.
mahesh
Mahesh
Hello, World!
Hi, Python!
Hello, World!
Hi, Python!
Hi, Sun!
Hello, Summer!
Hi, See!