Python学习笔记(四)

文件和异常

读取文件内容:
with open('pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents)
无需关闭,python会帮你做这个事

python读取末尾时,会返回一个空字符串,表现为多一个空行,去除空行:
with open('pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents.rstrip())

Linux读取某路径下文件:
file_path = '/home/ehmatthes/other_files/text_files/filename.txt'
with open(file_path) as file_object:
window读取某路径下文件:
file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt'
with open(file_path) as file_object:


逐行读取文件内容:
with open('w.py') as file_test:
	for line in file_test:
		print(line)
逐行读取文件内容(去除空行):
with open('w.py') as file_test:
	for line in file_test:
		print(line.rstrip())

with读取的文件对象只在with代码块发生作用,外部使用时需要保存到列表中
filename = 'w.py'
with open(filename) as file_object:
	lines = file_object.readlines()
for line in lines:
	print(line.rstrip())
写入文件:
filename = 'programming.txt'
with open(filename, 'w') as file_object:
    file_object.write("I love programming.")
    file_object.write("I love creating new games.")

追加到文件:
filename = 'programming.txt'
with open(filename, 'a') as file_object:
    file_object.write("I also love finding meaning in large datasets.\n")
    file_object.write("I love creating apps that can run in a browser.\n")
捕获异常:
try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")

try-else逻辑(else是try成功时执行):
while True:
    first_number = input("\nFirst number: ")
    if first_number == 'q':
        break
    second_number = input("Second number: ")
    try:
        answer = int(first_number) / int(second_number)
    except ZeroDivisionError:
        print("You can't divide by 0!")
    else:
        print(answer)

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值