- exceptions
- assertions
Burkay Genç, Ahmet Selman Bozkır, and Selma Dilek
17/05/2023
A text file can be thought of as a sequence of lines
MUH101 Introduction to Programming A Course By Burkay Genc 2019-2020 Spring Topics: 1 - Introduction 2 - Branching and Iteration 3 - Iterations ...
You can download this file from here
open()
functionopen()
returns a file handle - a variable used to perform operations on the fileopen()
handle = open(filename, mode)
returns a handle used to manipulate the file
filename
is a string
mode
is optional and should be
muh101_file = open("muh101.txt", "r") muh101_file
## <_io.TextIOWrapper name='muh101.txt' mode='r' encoding='cp65001'>
muh101_file.close()
handle.close()
muh101_file = open("muh100.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'muh100.txt'
newline
Character\n
in stringsstuff = "Hello\nWorld!" stuff
## 'Hello\nWorld!'
print(stuff)
## Hello ## World!
len(stuff)
## 12
A text file can be thought of as a sequence of lines
MUH101 Introduction to Programming A Course By Burkay Genc 2019-2020 Spring Topics: 1 - Introduction 2 - Branching and Iteration 3 - Iterations ...
MUH101 Introduction to Programming\n A Course By Burkay Genc\n 2019-2020 Spring\n \n Topics:\n 1 - Introduction\n 2 - Branching and Iteration\n 3 - Iterations\n ...
xfile = open('muh101.txt', 'r') for line in xfile: print(line, end="")
## MUH101 Introduction to Programming ## A Course By Burkay Genc ## 2019-2020 Spring ## ## Topics: ## 1 - Introduction ## 2 - Branching and Iteration ## 3 - Iterations ## 4 - Functions and Scope ## 5 - Functions and Recursion ## 6 - Tuples and Lists ## 7 - Dictionaries ## 8 - Testing and Debugging ## 9 - Exceptions and Assertions ## 10 - File IO
xfile.close()
fhand = open('muh101.txt', 'r') count = 0 for line in fhand: count = count + 1 print('Line Count:', count)
## Line Count: 15
fhand.close()
We can read the whole file (newlines and all) into a single string using the handle.read()
function
fhandle = open('muh101.txt', 'r') wholeContent = fhandle.read() print(wholeContent)
## MUH101 Introduction to Programming ## A Course By Burkay Genc ## 2019-2020 Spring ## ## Topics: ## 1 - Introduction ## 2 - Branching and Iteration ## 3 - Iterations ## 4 - Functions and Scope ## 5 - Functions and Recursion ## 6 - Tuples and Lists ## 7 - Dictionaries ## 8 - Testing and Debugging ## 9 - Exceptions and Assertions ## 10 - File IO
fhandle.close()
You can provide an integer to read that many characters from the file:
fhandle = open('muh101.txt', 'r') wholeContent = fhandle.read(100) print(wholeContent)
## MUH101 Introduction to Programming ## A Course By Burkay Genc ## 2019-2020 Spring ## ## Topics: ## 1 - Introducti
fhandle.close()
We can put an if statement in our for loop to only print lines that meet some criteria
fhandle = open('muh101.txt') for line in fhandle: if line.startswith('3') or line.startswith('5'): print(line)
## 3 - Iterations ## ## 5 - Functions and Recursion
fhandle.close()
print()
adds a newline by defaultrstrip()
function to remove the newlines from each linefhandle = open('muh101.txt') for line in fhandle: line = line.rstrip() if line.startswith('3') or line.startswith('5'): print(line)
## 3 - Iterations ## 5 - Functions and Recursion
fhandle.close()
rstrip
removes extra whitespaces from strings
We can conveniently skip a line by using the continue statement
fhandle = open('muh101.txt') i = 0 for line in fhandle: i += 1 line = line.rstrip() if i < 5: # Skip the first 4 lines continue print(line)
## Topics: ## 1 - Introduction ## 2 - Branching and Iteration ## 3 - Iterations ## 4 - Functions and Scope ## 5 - Functions and Recursion ## 6 - Tuples and Lists ## 7 - Dictionaries ## 8 - Testing and Debugging ## 9 - Exceptions and Assertions ## 10 - File IO
fhandle.close()
We can look for a string anywhere in a line as our selection criteria
fhandle = open('muh101.txt') for line in fhandle: line = line.rstrip() if 'and' in line: # Print the line only if it contains 'and' print(line)
## 2 - Branching and Iteration ## 4 - Functions and Scope ## 5 - Functions and Recursion ## 6 - Tuples and Lists ## 8 - Testing and Debugging ## 9 - Exceptions and Assertions
fhandle.close()
try: fhandle = open("muh100.txt") print("File contains", len(fhandle.read()), "characters.") except: print("File not found!")
## File not found!
fhandle = open("muh102.txt", "w") fhandle.write("test string") # Outputs number of written characters
## 11
fhandle.close()
We can now read from newly created muh102.txt
:
fhandle = open("muh102.txt", "r") print(fhandle.read())
## test string
fhandle.close()
fhandle = open("muh102.txt", "w") fhandle.write("another string")
## 14
fhandle.close() fhandle = open("muh102.txt", "r") print(fhandle.read())
## another string
fhandle.close()
'a'
, mode to avoid this behaviour.fhandle = open("muh102.txt", "a") fhandle.write("appended string")
## 15
fhandle.close() fhandle = open("muh102.txt", "r") print(fhandle.read())
## another stringappended string
fhandle.close()
\n
to write to a new line
fhandle.write("\nappended string")
There are many other modes besides ‘r’, ‘w’ and ‘a’
fhandle = open("squares.txt", "w") for i in range(1, 11): fhandle.write(str(i**2) + "\n")
## 2 ## 2 ## 2 ## 3 ## 3 ## 3 ## 3 ## 3 ## 3 ## 4
fhandle.close()
Check the file:
fhandle = open("squares.txt", "r") print(fhandle.read())
## 1 ## 4 ## 9 ## 16 ## 25 ## 36 ## 49 ## 64 ## 81 ## 100
fhandle.close()
with open
The with
statement works with the open()
function to open a file. Unlike open()
where you have to close the file with the close()
method, the with
statement closes the file for you.
with open("squares.txt", "r") as fhandle: lines = fhandle.readlines() print(lines)
## ['1\n', '4\n', '9\n', '16\n', '25\n', '36\n', '49\n', '64\n', '81\n', '100\n']
readlines()
returns all lines in the file, as a list where each line is an item in the list object.These slides are a direct adaptation of the slides used on the Py4e Webpage.
Original work by:
Dr. Charles R. Severance
Adapted by and for:
Asst. Prof. Dr. Burkay Genç. MUH101 Introduction to Programming, Spring 2020. Hacettepe University, Computer Engineering Department.