python文件和异常

代码对文件的操作,是我一直以来都很感兴趣的事情

文件

读文件

1.最简单的打开文件:(没法读取中文,文件中有中文则报错)

with open('路径') as file:
	contes = file.read() 
	print(contens.rstrip())		#删除多余空白,因为文件自带一个换行,print自动输出一个换行

#还可以这样
file = open('路径')
print(file)

2.逐行读取:

filename = '路径'

with open(filename) as file:
	for line in file:
		print(line)


#其他方法
with open(filename) as file:
	lines = file.readlines()
	
#lines是一个列表,这样的话这个文件内的元素就可以在with代码块以外使用了。

for line in lines:
	print(line)

3.读取出来的文件的类型还是字符串。

4.abc.replace(‘qwe’,‘asd’),可以吧abc字符串内的全部qwe替换为asd


有读就有写,能过桥就能回来

#写文件

filename = '路径'  #文件不存在的话,自动创建新的

with open(filename,'w') as file:
	file.write("I Love You")		

r 读文件
w 写文件,清空文件内原来的内容
a 附加模式,与w相反
+ 混合使用 [ra,rw]

2.同样写入党也只能是字符串,想存其他类型的话,需要先转换成字符串。

3.write()不会自动加入换行符,需要的话手动添加。


异常

1.ZeroDivisionError 除数等于0的时候报错。

print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")

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:		#有错误的话运行except内的代码,没的话跳过
        print("You can't divide by 0!")
    else:		#try运行成功后,运行else内的代码。
        print(answer)

2.FileNotFoundError 文件不存在的时候报错。

filename = 'alice.txt'

try:
    with open(filename) as f_obj:
        contents = f_obj.read()
except FileNotFoundError :
    msg = "Sorry, the file " + filename + " does not exist."
    print(msg)
    #pass  失败时一声不吭
else:
    # Count the approximate number of words in the file.
    words = contents.split()
    num_words = len(words)
    print("The file " + filename + " has about " + str(num_words) + " words.")

title = 'Alice in wonderland'
title.split()		#以空格为分隔符,将字符串拆成多个部分。

#运行结果为:['Alice' , 'in' , 'wonderland']

数据存取

1.将数据存下来,待到下次运行时,可以保存这个结果,比如说游戏存档。

2.需要用到json库。

json.dump() , 存,接收两个实参,数据和文件对象
json.load() , 取

import json
#存
numbers = [2, 3, 5, 7, 11, 13]

filename = 'numbers.json'
with open(filename, 'w') as file_object:
    json.dump(numbers, file_object)

#取

with open(filename) as file_object:
    numbers = json.load(file_object)
    
print(numbers)

posted @ 2019-12-17 19:31  lcyok  阅读(191)  评论(0)    收藏  举报