python 文件操作

####################
# 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就会跳转到对应异常处理代码,比如打印异常提示

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值