Day
Python for Data Science
10 Read Write Files
To read a text file in Python, you follow these steps:
•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>)
Relative or absolute path to A string (character) that
the file (including the extension) indicates what you want
to do with the file.
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
# Reading the txt file
file_name = "[Link]"
file = open(file_name, "r")
content = [Link]()
print(content)
English,Charles Severance
English,Sue Blumenberg
English,Elloitt Hauser
Spanish,Fernando TardÃo Muñiz
# Printing the path of file
print([Link])
# Printing the mode of file
print([Link])
# Printing the file with '\n' as a new file
print(content)
# Printing the type of file
print(type(content))
[Link]
r
English,Charles Severance
English,Sue Blumenberg
English,Elloitt Hauser
Spanish,Fernando TardÃo Muñiz
<class 'str'>
# Close the file
[Link]()
# Verificati on of the closed file
[Link]
True
Another way to read a file
Variable that will be used
Keyword File Object to refer to the file object
with open(”<file>”, “<mode>”) as <var>:
#Do what you need with the file
# Verification of the closed file
[Link]
True
# See the content of the file
print(content)
English,Charles Severance
English,Sue Blumenberg
English,Elloitt Hauser
Spanish,Fernando TardÃo Muñiz
# Reading the first 20 characters in the text file
fname = '[Link]'
with open(fname, 'r') as f:
print([Link](20))
English,Charles Seve
# Reading certain amount of characters in the file
fname = '[Link]'
with open(fname, 'r') as f:
print([Link](10))
print()
print([Link](20))
print()
print([Link](50))
print()
print([Link](100))
English,Ch
arles Severance
Engl
ish,Sue Blumenberg
English,Elloitt Hauser
Spanish,
Fernando TardÃo Muñiz
# Reading first line in the text file
with open(fname, 'r') as f:
print('The first line is: ', [Link]())
The first line is: English,Charles Severance
# Difference between read() and readline()
with open(fname, 'r') as f:
print([Link](10))
print()
print([Link](20)) # This code returns the next 20 characters in
the line.
English,Ch
arles Severance
Engl
Loop usage in the text file
with open(fname, 'r') as f:
line_number = 1
for line in f:
print('Line number', str(line_number), ':', line)
line_number+=1
Line number 1 : English,Charles Severance
Line number 2 : English,Sue Blumenberg
Line number 3 : English,Elloitt Hauser
Line number 4 : Spanish,Fernando TardÃo Muñiz
Methods
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.
with open(fname, 'r') as f:
print([Link]())
English,Charles Severance
English,Sue Blumenberg
English,Elloitt Hauser
Spanish,Fernando TardÃo Muñiz
with open(fname, 'r') as f:
print([Link](30))
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.
with open(fname, 'r') as f:
content=[Link]()
print(content)
['English,Charles Severance\n', 'English,Sue Blumenberg\n', 'English,Elloitt Hauser
\n', 'Spanish,Fernando TardÃo Muñiz\n']
strip() function
Removes the leading and trailing spaces from the given string.
with open(fname, 'r') as f:
len_file = 0
total_len_file = 0
for line in f:
# Total length of line in the text file
total_len_file = total_len_file+len(line)
# Lenght of the line after removing leading and trailing spaces
len_file = len_file+len([Link]())
print(f'Total lenght of the line is {total_len_file}.')
print(f'The length of the line aft er removing leading and trail-
ing spaces is {len_file}.')
Total lenght of the line is 106.
The length of the line aft er removing leading and trailing spaces is 102.
Size of the text file
with open(fname, 'r') as f:
str = ""
for line in f:
str+=line
print(f'The size of the text file is {len(str)}.')
The size of the text file is 26.
The size of the text file is 49.
The size of the text file is 72.
The size of the text file is 106.
Number of lines in the text
with open(fname, 'r') as f:
count = 0
for line in f:
count = count + 1
print(f'The number of lines in the text file is {count}.')
The number of lines in the text file is 1.
The number of lines in the text file is 2.
The number of lines in the text file is 3.
The number of lines in the text file is 4.
Writing Files in Python To write to a text file in Python, you follow these steps:
•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(”[Link]”,”w”)
for x in range (4): Repeat the
process 4 times
name = input(”Enter name”)
Write inside the file [Link](name+”\n”)
[Link]()
Asks user for a
name
Closes the file Move to a
new line
Character Function
r Open file for reading only. Starts reading from beginning
of file. This default mode.
rd Open a file for reading only in binary format. Starts
reading from beginning of file.
Open file for reading and writing. File pointer placed at\
r+ beginning of the file.
Open file for writing only. File pointer placed at beginning
w of the file. Overwrites existing file and creates a new one
if it does not exists.
wb Same as w but opens in binary mode.
w+ Same as w but also alows to read from file.
wb+ Same as wb but also alows to read from file.
a Open a file for appending. Starts writing at the end of file.
Creates a new file if file doesnot exist.
ab Same as a but in binary format. Creates a new file if file
does not exist.
a+ Same as a but also open for reading.
ab+ Same as ab but also open for reading.
# Writing lines to a file.
fname = 'pcr_file.txt'
with open(fname, 'w') as f:
[Link]("I dedicate this book to Nancy Lier Cosgrove Mullis.\n")
[Link]("Jean-Paul Sartre somewhere observed that we each of us
make our own hell out of the people around us.")
# Checking the file whether it was written or not
with open(fname, 'r') as f:
content = [Link]()
print(content)
I dedicate this book to Nancy Lier Cosgrove Mullis.
Jean-Paul Sartre somewhere observed that we each of us make our own hell
out of the people around us.
Appending files
# Wrting and then reading the file
new_file = 'pcr_file.txt'
with open(new_file, 'w') as f:
[Link]('Overright\n')
with open(new_file, 'r') as f:
print([Link]())
Overright
Other modes
a+
Appending and Reading. Creates a new file, if none exists.
fname = 'pcr_file.txt'
with open(fname, 'a+') as f:
[Link]("From F. Lee Bailey\n")
# To verify the text file whether it is added or not
with open(fname, 'r') as f:
print([Link]())
Overright
From F. Lee Bailey
tell() and seek() functions with a+
with open(fname, 'a+') as f:
print("First location: {}".format([Link]())) # it returns the
current position in bytes
content = [Link]()
if not content:
print('Read nothing.')
else:
print([Link]())
[Link](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: [Link](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([Link]()))
content = [Link]()
if not content:
print('Read nothing.')
else:
print(content)
print('Locati on aft er reading: {}'.format([Link]()))
First location: 31
Read nothing.
Second locati on: 0
Overright
From F. Lee Bailey
Locati on aft er reading: 31
•r+ Reading and writing. Cannot truncate the file.
with open(fname, 'r+') as f:
content=[Link]()
[Link](0,0) # writing at the beginning of the file
[Link]('From The San Diego Union-Tribune' + '\n')
[Link]("Refreshing … brashly confident … indisputably entertain-
ing." + "\n")
[Link]("To my family..." + '\n')
[Link](0,0)
print([Link]())
From The San Diego Union-Tribune
Refreshing … brashly confident … indisputably entertaining.
To my family...
From The San Diego Union-Tribune
Refreshing … brashly confident … indisputably entertaining.
To my family...
Copy the file
# Let's copy the text file 'pcr_file.txt' to another one 'pcr_-
file_1.txt'
fname = 'pcr_file.txt'
with open(fname, 'r') as f_reading:
with open('pcr_file_1.txt', 'w') as f_writing:
for line in f_reading:
f_writing.write(line)
# For the verificati on, execute the following codes
fname = 'pcr_file_1.txt'
with open(fname, 'r') as f:
print([Link]())
# Now, there are 2 files from the same file content.
From The San Diego Union-Tribune
Refreshing … brashly confident … indisputably entertaining.
To my family...
From The San Diego Union-Tribune
Refreshing … brashly confident … indisputably entertaining.
To my family...
# Writi ng the student names into a file
fname = open(r'student_name.txt', 'w')
for i in range(3):
name = input('Enter a student name: ')
[Link](name)
[Link]('\n') # To write names as a new line
fname = open(r'student_name.txt', 'r')
for line in fname:
print(line)
[Link]()
Enter a student name: mahesh
Enter a student name: mahesh
Enter a student name: mahesh
mahesh
mahesh
Mahesh
lines = ['Hello, World!', 'Hi, Python!']
with open('new_file.txt', 'w') as f:
for line in lines:
[Link](line)
[Link]('\n')
with open('new_file.txt', 'r') as f:
print([Link]())
Hello, World!
Hi, Python!
# Add more lines into the file
more_lines = ['Hi, Sun!', 'Hello, Summer!', 'Hi, See!']
with open('new_file.txt', 'a') as f:
[Link]('\n' .join(more_lines))
with open('new_file.txt', 'r') as f:
print([Link]())
[Link]()
Hello, World!
Hi, Python!
Hi, Sun!
Hello, Summer!
Hi, See!