Python provides facilities to work with files. The open() function returns a file object, and is most commonly used with two arguments:
open(filename, mode)
The mode argument is optional, 'r' is used by default
f = open('my_file.txt', 'w+')
print(f.name, f.closed, f.mode)
f.write('0123456789')
f.seek(5)
f.write('Hello, World!')
f.read()
f.close()
print(f.name, f.closed, f.mode)
f = open('my_file_2.txt', 'w')
print("cursor: %d" % f.tell())
for i in range(10):
print("cursor: %d" % f.tell())
f.write('This is line %d\n' % i)
print("cursor: %d" % f.tell())
f.close()
f = open('my_file_2.txt', 'r')
print("Read all file: ")
f.seek(0, 0)
print(f.read())
print("Read file by lines: ")
f.seek(0, 0)
for line in f:
print(line)
print("Read all lines from file: ")
f.seek(0, 0)
lines = f.readlines()
print(lines)
f.close()
f = open('my_file_3.txt', 'w')
for i in range(10):
print(i, file=f)
f.close()
f = open('my_file_3.txt', 'r')
print(f.read())
f = open('my_file_3.txt', 'r+')
f.seek(0, 0)
for i in range(10):
f.write(str(i))
f.write('\t')
f.seek(0, 0)
data = []
for line in f:
data.append(list(map(int, line.split())))
f.close()
for d in data:
print(d)
List of Python builtin exceptions: https://docs.python.org/3/library/exceptions.html
# Missing colon ':'
for i in range(10)
print('HELLO')
# Invalid indentation
for i in range(10):
print('HELLO')
# Bad operand type or bad operation
x = '10'
y = 2
z = x / y
# Division by zero
x = 10
y = 0
z = x // y
# List index out of bounds
x = [1,2,3]
print(x[3])
# Modifying a tuple
y = (1, 2, 3)
y[0] = 10
# Undefined variable
zz = xx + yy
# Invlid value format
x = int('ABS') # Not a number
x = 10
y = 0
try:
z = x // y
except ZeroDivisionError:
print("Please do not divide by zero!")
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("It was not a number. Please try again...")
def input_int():
try:
return int(input())
except:
return -1
for i in range(5):
print("x = %d" % input_int())
print("Before try")
try:
print(" Before exception")
x = int(input())
y = 10 / x
print(" After exception")
except ValueError:
print(" In except ValueError")
except ZeroDivisionError:
print(" In except ZeroDivisionError")
else:
print(" In else")
finally:
print(" In finally")
print("After try")
f = open('my_file_4.txt', 'w')
try:
for i in range(10):
print("Writing line %d" % i)
f.write('Line %d' % i)
f.write('\n')
if i == 8:
raise Exception("i == 8")
finally:
print("File will be closed no matter what happens!")
f.close()
with open('my_file_5.txt', 'w') as f:
for i in range(10):
print("Writing line %d" % i)
f.write('Line %d' % i)
f.write('\n')
if i == 8:
raise Exception("i == 8")
def func(a, b):
if not (0 <= a <= 100):
raise Exception("a = %d" % a)
if not (0 <= b <= 100):
raise Exception("b = %d" % b)
return a * b
a = int(input())
b = int(input())
try:
print(func(a, b))
except Exception as e:
print("Error: %s" % e)
##### Assertions
def add_two_numbers(a, b):
assert a > 0, "a must be positive"
assert b > 0, "b must be positive"
return a + b
x = add_two_numbers(1, 2)
assert x == 3
print(x)
x = add_two_numbers(1, -2)
assert x == 3
print(x)
Do it in PyCharm. Put breakpoints into this code and explore different paths in the control flow.
def fact(n):
if n == 1:
return n
else:
return n * fact(n-1)
def func(x, y):
if x < 0 or y < 0:
raise ValueError
return fact(y) / x
x = int(input())
y = int(input())
try:
if x > y:
v = func(x, y)
else:
v = func(y, x)
print("Result: ", v)
except:
print("Something went wrong")
You are given a list with 10 prime numbers, already in your code. Write a program that asks the user for an index i and outputs the i-th prime number.
Using the example below, write similar code that allows you to enter anything into the input field without crashing the program.
Simpler version: if the input is incorrect, output an error message and end the program.
Complex version: ask the user to enter the correct number, similar to the example below.
If the number is correct, you quit.
If the number is incorrect, you ask the user if they want to continue.
If they want to continue, you repeat the program.
If they don't want to continue, you quit.
a_list = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
input_index = int(input())
# ValueError = input is of incorrect data type
print(a_list[input_index])
# IndexError = list index out or range
with open('data.txt', 'w') as datafile:
print('1 2 3 4 5', file=datafile)
cont_flag = True
while cont_flag:
filename = input('Please input file name: ')
try:
with open(filename) as datafile:
print(datafile.read())
cont_flag = False
except FileNotFoundError as error:
print(error)
print('File does not exist')
if cont_flag:
cont_text = input('Enter Y to try again ')
print(cont_text)
if cont_text != 'Y' and cont_text != 'y':
cont_flag = False
Write a program that saves a string "Example data" to a file and then reads it back. Remember to close the file before you open it again. Use the with statement to do it.
print(cont_flag)
pickle
is a Python module used for serialization, or storing a Python object structure as a binary file (or other byte stream).
It is useful in various applications, including saving the state of your work so you can return to it in the future.
If you want to save some object, use pickle.dump(object, file)
If you want to load your saved file, use pickle.load(file)
If you want to save an object you defined on your own (like a function or a class), you have to import it before loading.
You can't save everything, but this should be enough for simple applications.
import pickle
# An arbitrary collection of objects supported by pickle.
data = {
'a': [1, 2.0, 3, 4+6j],
'b': ("character string", b"byte string"),
'c': {None, True, False}
}
with open('data.pickle', 'wb') as f:
# Pickle the 'data' dictionary using the highest protocol available.
pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
import pickle
with open('data.pickle', 'rb') as f:
# The protocol version used is detected automatically, so we do not
# have to specify it.
data = pickle.load(f)
print(data)
Write the following program.
The user inputs integer numbers into the program. The numbers are saved into a list. If the user inputs 0, it is a sign that the input has ended. The number 0 itself shouldn't be included into the list. The list is empty at the start.
The program should be persistent: once the user runs it again, it should load all the previously inputted numbers and append the new ones at the end of the list.
To achieve this, pickle the list at the end and unpickle it at the beginning of the program. When you run the program for the first time, the pickled file from "the last time" wouldn't exist. Write an exception handler to output a notice message "New file" in this case, then append the numbers to an empty list and pickle the list.
import pickle
data = []