####################
# file operations
####################
# create a file
f = open("demo.txt", "w") # w -- create and write
f.write("The first line of data.")
f.write("The second line of data.")
f.close()
f = open("demo.txt", "r") # r -- read
print(f.read())
f.close()
# using \n to change lines
f = open("demo.txt", "a") # a -- append
f.write("\nThe third line of data.")
f.write("\nThe forth line of data.")
f.close()
f = open("demo.txt", "r") # r -- read
print(f.read())
f.close()
# read lines in a file to a list
f = open("demo.txt", "r") # r -- read
alist = []
alist = f.readlines()
print(alist)
f.close()
# read lines in a file to a list, but remove all "\n"
f = open("demo.txt", "r") # r -- read
alist = []
for line in f:
alist.append(line.strip("\n"))
print(alist)
f.close()
# print each individual words, one in a line, in the first line of demo.txt
print(alist[0])
words = alist[0].split(" ") # words is a list
for word in words:
if "." in word:
ws = word.split(".") # ws is a list
for w in ws:
print(w)
else:
print(word)
# exercise: create a file and store the first 50 items of Fibonacci sequence
# 1, 1, 2, 3, 5, 8, 13, 21, ...
f = open("fib.txt", "w")
f.write("1\n")
f.write("1\n")
a, b = 1, 1
for i in range(48):
c = a+b
f.write(str(c)+"\n")
a = b
b = c
f.close()
# read the data in fib.txt into a list
f = open("fib.txt", "r")
alist = []
for line in f:
num = line.strip("\n") # step 1. remoe "\n
num = int(num) # step 2. convert to number
alist.append(num) # step 3. append it to the list
print(alist)
####################
# exception handling
####################
a = input("Enter a number for a: ")
b = input("Enter a number for b: ")
sum = int(a) + int(b)
print(sum)
while True:
a = input("Enter a number for a: ")
b = input("Enter a number for b: ")
try:
sum = int(a) + int(b)
break
except ValueError:
print("Oops! You entered an invalid number. Try again...")
print(sum)
# divided by 0
def division(x, y):
z = 0
cubic = 0
try:
z = x/y
except ZeroDivisionError:
print("Oops! Divided by 0!")
else:
cubic= z**3
finally:
return z, cubic
print(division(3, 0))
其中的 try
为python的捕捉异常功能,例如在这段代码中
try:
sum = int(a) + int(b)
break
except ValueError:
print("Oops! You entered an invalid number. Try again...")
程序到这里会执行try
子句sum = int(a) + int(b)
如果出现了下面列举的异常,如ValueError
就会跳转到对应异常处理代码,比如打印异常提示