Most commonly used commands and functions that are used for reading and writing text files in Python 3.x. Therefore, these commands are used for manipulating file objects.
2. Reading files
● To open a file and read: f = open('name-of-the-file.txt', 'r')
● To open a file and write: f = open('name-of-the-file.txt', 'w')
● To open a file and append(this is done to avoid overwriting of a file and include extra chunk of text to
the file which has already been created): f = open('name-of-the-file.txt', 'a')
● To open a file and read and write: f = open('name-of-the-file.txt', 'r+')
● Prints the name of the file: print(f.name)
● Prints the mode if file is read or write mode: print(f.mode)
● Prints the file contents in the python interpreter or terminal/cmd: print(f.read)
● Reads the first line. Will read second line if this method is called again:
f_contents = f.readline()
print(f_contents)
● Reads each line of the .txt file and stores it in a list variable:
f_contents = f.readlines()
print(f_contents)
● Download the files: mbox.txt and mbox-short.txt for practice from: www.py4e.com/code3/mbox.txt
and www.py4e.com/code3/mbox-short.txt
● To read each lines of the whole file in traditional way:
fname = input('Enter the file name: ')
try:
fhand = open(fname, 'r')
# Reads each line in the file
count = 0
for line in fhand:
# end = '' removes extra line
print(line, end='')
count = count + 1
fhand.close()
except FileNotFoundError:
print('File: ' + fname + ' cannot be opened.')
# Terminates the program
exit()
print('There were', count, 'subject lines in', fname)
● To read a line which starts with string 'From:':
for line in fhand:
if line.startswith('From:'):
print(line, end='')
2
3. ● To read the whole file:
fname = input('Enter the file name: ')
try:
fhand = open(fname, 'r')
text = fhand.read()
fhand.close()
except FileNotFoundError:
print('File cannot be opened:', fname)
exit()
print(text)
● To read each line of the file and the line starting from 'From:' using context manager:
fname = input('Enter the file name: ')
try:
with open(fname, 'r') as f:
for line in f:
if line.startswith('From:'):
print(line, end='')
except FileNotFoundError:
print('File cannot be opened:', fname)
exit()
● To read whole file using context manager:
fname = input('Enter the file name: ')
try:
with open(fname, 'r') as f:
text = f.read()
except FileNotFoundError:
print('File cannot be opened:', fname)
exit()
print(text)
● To read specified number of characters from the file:
fname = input('Enter the file name: ')
with open(fname, 'r') as f:
size_to_read = 10
f_contents = f.read(size_to_read)
# Infinite loop for testing
3
4. while len(f_contents) > 0:
# To identify if we are looping through 10
# characters at a time use end='*'
print(f_contents, end='*')
Write to files
● To make a new file and write to it:
fout = open('out.txt', 'w')
line1 = "This here's the wattle, n"
fout.write(line1)
line2 = 'the emblem of our land.n'
fout.write(line2)
● To make a copy of the file:
fname = input('Enter the file name: ')
with open(fname, 'r') as rf:
with open(fname[:-4] + '_copy.txt', 'w') as wf:
for line in rf:
wf.write(line)
● To add content to an already written file such that overwriting doesn’t occur by going append mode
from write mode:
oceans = ["Pacific", "Atlantic", "Indian", "Southern", "Arctic"]
with open("oceans.txt", "w") as f:
for ocean in oceans:
print(ocean, file=f)
with open("oceans.txt", "a") as f:
print(23*"=", file=f)
print("These are the 5 oceans.", file=f)
● To make a copy of other files such as .jpeg and .pdf, read binary and write binary mode has to be
enabled:
with open('file-of-your-choice.jpg', 'rb') as rf:
with open('file-of-your-choice_copy.jpg', 'wb') as wf:
for line in rf:
wf.write(line)
4
5. References
YouTube. 2018. Python Tutorial: File Objects - Reading and Writing to Files - YouTube. [ONLINE]
Available at: https://www.youtube.com/watch?v=Uh2ebFW8OYM. [Accessed 28 March 2018].
YouTube. 2018. Text Files in Python || Python Tutorial || Learn Python Programming - YouTube.
[ONLINE] Available at: https://www.youtube.com/watch?v=4mX0uPQFLDU. [Accessed 28 March
2018].
Severance, C., 2016. Python for Everybody. Final ed. New York, USA: Creative Commons
Attribution-NonCommercial- ShareAlike 3.0 Unported License.
5