Write and Save Files in Python: Objectives
Write and Save Files in Python: Objectives
Objectives
After completing this lab you will be able to:
https://labs.cognitiveclass.ai/tools/jupyterlab/lab/tree/labs/PY0101EN/PY0101EN-4-2-WriteFile.ipynb?lti=true 1/11
2/25/22, 10:13 AM PY0101EN-4-2-WriteFile
Table of Contents
Writing Files
We can open a file object using the method write() to save the text file to a list. To write to a file, the mode
argument must be set to w. Let’s write a file Example2.txt with the line: “This is line A”
In [ ]:
exmp2 = '/resources/data/Example2.txt'
In [ ]:
# Read file
print(testwritefile.read())
https://labs.cognitiveclass.ai/tools/jupyterlab/lab/tree/labs/PY0101EN/PY0101EN-4-2-WriteFile.ipynb?lti=true 2/11
2/25/22, 10:13 AM PY0101EN-4-2-WriteFile
In [ ]:
The method .write() works similar to the method .readline() , except instead of reading a new line it
writes a new line. The process is illustrated in the figure. The different colour coding of the grid represents a new
line added to the file after each method call.
You can check the file to see if your results are correct
In [ ]:
print(testwritefile.read())
In [ ]:
Lines = ["This is line A\n", "This is line B\n", "This is line C\n"]
Lines
In [ ]:
print(line)
writefile.write(line)
We can verify the file is written by reading it and printing out the values:
https://labs.cognitiveclass.ai/tools/jupyterlab/lab/tree/labs/PY0101EN/PY0101EN-4-2-WriteFile.ipynb?lti=true 3/11
2/25/22, 10:13 AM PY0101EN-4-2-WriteFile
In [ ]:
print(testwritefile.read())
However, note that setting the mode to w overwrites all the existing data in the file.
In [ ]:
writefile.write("Overwrite\n")
print(testwritefile.read())
Appending Files
We can write to files without losing any of the existing data as follows by setting the mode argument to append:
a. you can append a new line as follows:
In [ ]:
You can verify the file has changed by running the following cell:
In [ ]:
print(testwritefile.read())
Additional modes
https://labs.cognitiveclass.ai/tools/jupyterlab/lab/tree/labs/PY0101EN/PY0101EN-4-2-WriteFile.ipynb?lti=true 4/11
2/25/22, 10:13 AM PY0101EN-4-2-WriteFile
It's fairly ineffecient to open the file in a or w and then reopening it in r to read any lines. Luckily we can access
the file in the following modes:
You dont have to dwell on the specifics of each mode for this lab.
In [ ]:
print(testwritefile.read())
There were no errors but read() also did not output anything. This is because of our location in the file.
Most of the file methods we've looked at work in a certain location in the file. .write() writes at a certain
location in the file. .read() reads at a certain location in the file and so on. You can think of this as moving
your pointer around in the notepad to make changes at specific location.
Opening the file in w is akin to opening the .txt file, moving your cursor to the beginning of the text file, writing
new text and deleting everything that follows.
Whereas opening the file in a is similiar to opening the .txt file,
moving your cursor to the very end and then adding the new pieces of text.
It is often very useful to know where the 'cursor' is in a file and be able to control it. The following methods allow
us to do precisely this -
https://labs.cognitiveclass.ai/tools/jupyterlab/lab/tree/labs/PY0101EN/PY0101EN-4-2-WriteFile.ipynb?lti=true 5/11
2/25/22, 10:13 AM PY0101EN-4-2-WriteFile
In [ ]:
data = testwritefile.read()
print('Read nothing')
else:
print(testwritefile.read())
data = testwritefile.read()
if (not data):
print('Read nothing')
else:
print(data)
Finally, a note on the difference between w+ and r+. Both of these modes allow access to read and write
methods, however, opening a file in w+ overwrites it and deletes all pre-existing data.
To work with a file on existing data, use r+ and a+. While using r+, it can be useful to add a .truncate()
method at the end of your data. This will reduce the file to your data and delete everything that follows.
In the following code block, Run the code as it is first and then run it with the .truncate() .
In [ ]:
data = testwritefile.readlines()
testwritefile.write("finished\n")
#testwritefile.truncate()
testwritefile.seek(0,0)
print(testwritefile.read())
Copy a File
https://labs.cognitiveclass.ai/tools/jupyterlab/lab/tree/labs/PY0101EN/PY0101EN-4-2-WriteFile.ipynb?lti=true 6/11
2/25/22, 10:13 AM PY0101EN-4-2-WriteFile
In [ ]:
writefile.write(line)
In [ ]:
print(testwritefile.read())
After reading files, we can also write data into files and save them in different file formats like .txt, .csv, .xls (for
excel files) etc. You will come across these in further examples
Now go to the directory to ensure the .txt file exists and contains the summary data that we wrote.
Exercise
Your local university's Raptors fan club maintains a register of its active members on a .txt document. Every
month they update the file by removing the members who are not active. You have been tasked with automating
this with your Python skills.
Given the file currentMem , Remove each member with a 'no' in their Active column. Keep track of each of the
removed members and append them to the exMem file. Make sure that the format of the original files in
preserved. (Hint: Do this by reading/writing whole lines and ensuring the header remains )
Run the code block below prior to starting the exercise. The skeleton code has been provided for you. Edit only
the cleanFiles function.
https://labs.cognitiveclass.ai/tools/jupyterlab/lab/tree/labs/PY0101EN/PY0101EN-4-2-WriteFile.ipynb?lti=true 7/11
2/25/22, 10:13 AM PY0101EN-4-2-WriteFile
In [ ]:
memReg = 'members.txt'
exReg = 'inactive.txt'
fee =('yes','no')
def genFiles(current,old):
writefile.write(data.format(rnd(10000,99999),date,fee[rnd(0,1)]))
writefile.write(data.format(rnd(10000,99999),date,fee[1]))
genFiles(memReg,exReg)
Now that you've run the prerequisite code cell above, which prepared the files for this exercise, you are ready to
move on to the implementation.
https://labs.cognitiveclass.ai/tools/jupyterlab/lab/tree/labs/PY0101EN/PY0101EN-4-2-WriteFile.ipynb?lti=true 8/11
2/25/22, 10:13 AM PY0101EN-4-2-WriteFile
In [ ]:
'''
This function should remove all rows from currentMem containing 'no'
'''
#TODO: Read each member in the currentMem (1 member per row) file into a list.
# Hint: Recall that the first line in the file is the header.
#TODO: iterate through the members and create a new list of the innactive members
# If a member is inactive, add them to exMem, otherwise write them into currentMem
memReg = 'members.txt'
exReg = 'inactive.txt'
cleanFiles(memReg,exReg)
print(readFile.read())
print(readFile.read())
The code cell below is to verify your solution. Please do not modify the code and run it to test your
implementation of cleanFiles .
https://labs.cognitiveclass.ai/tools/jupyterlab/lab/tree/labs/PY0101EN/PY0101EN-4-2-WriteFile.ipynb?lti=true 9/11
2/25/22, 10:13 AM PY0101EN-4-2-WriteFile
In [ ]:
def testMsg(passed):
if passed:
else :
testWrite = "testWrite.txt"
testAppend = "testAppend.txt"
passed = True
genFiles(testWrite,testAppend)
ogWrite = file.readlines()
ogAppend = file.readlines()
try:
cleanFiles(testWrite,testAppend)
except:
print('Error')
clWrite = file.readlines()
clAppend = file.readlines()
print("The number of rows do not add up. Make sure your final files have the same head
er and format.")
passed = False
if 'no' in line:
passed = False
break
else:
passed = False
print ("{}".format(testMsg(passed)))
https://labs.cognitiveclass.ai/tools/jupyterlab/lab/tree/labs/PY0101EN/PY0101EN-4-2-WriteFile.ipynb?lti=true 10/11
2/25/22, 10:13 AM PY0101EN-4-2-WriteFile
Author
Joseph Santarcangelo (https://www.linkedin.com/in/joseph-s-50398b136/?
utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA
SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkPY0101ENSkillsNetwork19487395-
2021-01-01)
Other Contributors
Mavis Zhou (https://www.linkedin.com/in/jiahui-mavis-zhou-a4537814a?
utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA
SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkPY0101ENSkillsNetwork19487395-
2021-01-01)
Change Log
Date (YYYY-MM-DD) Version Changed By Change Description
https://labs.cognitiveclass.ai/tools/jupyterlab/lab/tree/labs/PY0101EN/PY0101EN-4-2-WriteFile.ipynb?lti=true 11/11