Professional Documents
Culture Documents
BS Information Technology
Python Programming Language
Assignments |1
Assignment No. 7
File Handling
Learning Outcome
At the end of this activity, the student should be able to code the file handling statements using Python
PL.
Requirement
Sample Output
a = 40
b = 510 #added code for value
if a > b:
print(f"{a} is greater than {b}")
print("Testing control structures")
Output
Code Screenshot
"""
Opening a file using open()
-open() takes 2 parameters:
filename and the mode of
opening
-modes are: r(read), a(append),
w(write), x(create
* Create a file using Notepad
and save as myfile.txt
"""
ITL313-18 |Systems Integration and Architecture Laboratory Prepared by Prof. TCAlcantara, MSIT
College of Computer Studies
BS Information Technology
Python Programming Language
Assignments |2
f = open("myfile.txt", "r")
"""
-if the file is not in the same
directory as your .py file,
need to specify path
"""
f =
open("D:\\myfolder\myfile.txt",
"r")
'''
Reading a file
- use the read() method of a
file object
'''
f = open("myfile.txt", "r")
print(f.read())
"""
Reading a file
-we can also read a portion of
the text, you can specify how
many characters to return
"""
print(f.read(5))
#returns the first 5 characters
print(f.readline())
#reads one line
print(f.readline())
for x in f:
print(x)
#reads the entire file by line
"""
Closing a file
- we should always close a
file when done
with it (good practice in
programming)
"""
f.close()
ITL313-18 |Systems Integration and Architecture Laboratory Prepared by Prof. TCAlcantara, MSIT
College of Computer Studies
BS Information Technology
Python Programming Language
Assignments |3
"""
Writing into a file
- two modes of opening for
adding content ('a' and 'w')
"""
f = open("myfile.txt", "a")
#appends content
f.write("The file gets more
content!")
f.close()
f = open("myfile.txt", "r")
print(f.read())
f.close()
f = open("myfile2.txt", "r+")
#write (overwrite existing)
content
"""
Deleting files
-import the os module, and run
its os.remove() function
"""
import os
os.remove("myfile2.txt")
import os
if
os.path.exists("myfile3.txt"):
os.remove("myfile3.txt")
else:
print("The file does not
exist")
ITL313-18 |Systems Integration and Architecture Laboratory Prepared by Prof. TCAlcantara, MSIT
College of Computer Studies
BS Information Technology
Python Programming Language
Assignments |4
import os
os.rmdir("myfolder")
Reporting
1. Save this file as PDF following the filename “ITL313-18_section_A-
7_FileHandling_Surname.pdf” (ex: ITL313-18_3-BSIT-.1_A-7_FileHandling_Alcantara.pdf).
2. Upload your assignment to the folder you created in the shared Google Drive under ITL313-
18_Lab_Surname folder.
ITL313-18 |Systems Integration and Architecture Laboratory Prepared by Prof. TCAlcantara, MSIT