0% found this document useful (0 votes)
40 views14 pages

CENG240-2021 Week11 File Handling

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views14 pages

CENG240-2021 Week11 File Handling

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

METU Computer Engineering

CEng 240 – Spring 2021


Week 11
Sinan Kalkan

File Handling

Disclaimer: Figures without reference are from either from “Introduction to programming concepts
with case studies in Python” or “Programming with Python for Engineers”, which are both co-authored
by me.
This Week
METU Computer Engineering

¢ File Handling
§ Files and sequential access
§ Parsing
§ Termination of input
§ Formatting files
§ Binary files

2021 S. Kalkan - CEng 240 8


First Example
METU Computer Engineering

fpointer = open('firstexample.txt', "w")


fpointer.write("hello\n")
fpointer.write("how are\n")
fpointer.write("you?\n")
fpointer.close()

2021 S. Kalkan - CEng 240 10


Files and Sequential Access
METU Computer Engineering

fp = open("firstexample.txt","r") # the example file we created above

for i in range(3): # repeat 3 times


content = fp.read(4) # read 4 bytes in each step
print("> ", content) # output 4 bytes preceded by >

fp.close()

2021 S. Kalkan - CEng 240 11


Parsing
METU Computer Engineering

instr = '10.0 5.0 5.0’


outlst = []

# Go over each substring


for substr in instr.split(' ‘):
outlst += [float(substr)]
# Convert each element to float and append it to the list

OR: outlst = [ float(substr) for substr in instr.split(' ')]

2021 S. Kalkan - CEng 240 12


Opening/closing files
METU Computer Engineering

¢ Opening files:
§ open(filename, “r”) => open file for reading
§ open(filename, “w”) => open file for writing
§ open(filename, “a”) => open file for appending

¢ Closing file:
§ fileobject.close()

2021 S. Kalkan - CEng 240 13


Accessing Files Line by Line
METU Computer Engineering

pointlist = [(0,0), (10,0), (10,10), (0,10)]

fp = open("pointlist.txt", "w") # open file for writing


fp.write(str(len(pointlist))) # write list length
fp.write('\n’)

# Go over each point in the list


for (x,y) in pointlist: # for each x,y value in the list
fp.write(str(x)) # write x
fp.write(' ') # space as number separator
fp.write(str(y)) # write y
fp.write('\n') # \n as line separator
Produces file
fp.close() with content:

2021 S. Kalkan - CEng 240 14


Accessing Files Line by Line
METU Computer Engineering

Read file with content:

fp = open("pointlist.txt") # open file for reading

nextline = fp.readline() # read the first line


while nextline != '': # while read is successful
print(nextline) # output the line
nextline = fp.readline() # read the nextline

fp.close() # when nextline == '' loop terminates

2021 S. Kalkan - CEng 240 15


Termination of input
METU Computer Engineering

¢ There are two ways to stop reading input:


1. By reading a definite number of items.
§ Call read() or readline() functions for a fixed number of times.
2. By the end of the file.
§ Continue to read() or readline() until they return empty string ‘’.

fp = open("pointlist.txt") # open file for reading

nextline = fp.readline() # read the first line


while nextline != '': # until end of file
... # Do something with the read line
nextline = fp.readline() # read the next line

2021 S. Kalkan - CEng 240 16


Termination of input
METU Computer Engineering

¢ We can also use our own special “marker”


File contents:
30
3.4 2.1
5.1 3.2
EOLIST
1 1.5
2.0 2.5

2021 S. Kalkan - CEng 240 17


Binary Files
METU Computer Engineering

¢ A text file is human readable.


§ Each number is represented by the characters of the digits.
§ “3.1415926535897932384626433832795028” occupies 34
characters/bytes.
¢ Content of a binary file is directly the binary representation of
data
§ Number 3.1415926535897932384626433832795028 occupies 4 bytes
on a 32-bit computer.
§ But the file is not human-readable.
¢ Opening binary files: open(filename, ‘rb’) or open(filename,
‘wb’)
¢ struct module should be used for creating and interpreting
bytes
2021 S. Kalkan - CEng 240 19
Examples
METU Computer Engineering

¢ Read a CSV file

¢ Dice game exercise:


https://pp4e-workbook.github.io/chapters/file_handling/dice_game.html

2021 S. Kalkan - CEng 240 20


Final Words:
Important Concepts
METU Computer Engineering

¢ Sequential access. File access.


¢ Text files. Reading and writing text files.
Parsing a text file.
¢ End of file, new line.
¢ Formatting files.
¢ Binary files and binary file access.

2021 S. Kalkan - CEng 240 21


METU Computer Engineering

THAT’S ALL FOLKS!


STAY HEALTHY

2021 S. Kalkan - CEng 240 22

You might also like