python进阶(7)--文件与异常
阅读原文时间:2021年04月20日阅读:1

一、文件读取
二、文件写入
三、异常
四、存储数据

---------------------------------------分割线:正文--------------------------------------------------------

一、文件读取

1、with语句

#采用idea的sources root的相对路径
with open('..//data//pi_digits.txt') as file_object:
contents = file_object.read()
#打印同时剔除空行
print(contents.rstrip())

查看结果:

3.1415926535
8979323846
2643383279

2、绝对路径

file_path='D:/Users/Mr.White/PycharmProjects/pythonProject/data/pi_digits.txt'
with open(file_path) as file_object:
contents = file_object.read()
print(contents.rstrip())

查看结果:

3.1415926535
8979323846
2643383279

3、for循环逐行读取

with open('../data/pi_digits.txt') as file_object:
for line in file_object:
print(line.rstrip())

查看结果:

3.1415926535
8979323846
2643383279

4、readline()方法,将文件的内容存储在列表内

with open('../data/pi_digits.txt') as file_object:
lines=file_object.readlines()
for line in lines:
print(line.rstrip())

查看结果:

3.1415926535
8979323846
2643383279

优化代码,拼接字符串读取

with open('../data/pi_digits.txt') as file_object:
lines=file_object.readlines()
pi_string=''
for line in lines:
pi_string+=line.strip()
print(pi_string)
print(len(pi_string))

查看结果:

3.141592653589793238462643383279
32

二、文件写入

1、with,覆盖模式

file_name='../data/programming.txt'
with open(file_name,'w') as file_object:
file_object.write("I love programming.")

查看文件(../data/programming.txt):

I love programming.

2、写入多行

file_name='../data/programming.txt'
with open(file_name,'w') as file_object:
file_object.write("I love programming.\n")
file_object.write("i love creating new games.\n")

查看文件(../data/programming.txt):

I love programming.
i love creating new games.

3、with,附加模式

with open(file_name,'a') as file_object:
file_object.write("I also love fing…\n")
file_object.write("i love creating apps that…\n")

查看文件(../data/programming.txt):

I love programming.
i love creating new games.
I also love fing…
i love creating apps that…

三、异常

1、解决异常(ZeroDivisionError):try except

try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")

查看结果:

You can't divide by zero!

2、解决异常(FileNotFoundError):try except

filename="testfile.txt"
try:
with open(filename,encoding='utf-8') as f:
contents=f.read()
except FileNotFoundError:
print(f"sorry,the file {filename} does not exits.")

查看结果:

sorry,the file testfile.txt does not exits.

3、异常时静默处理:pass

try:
print(5/0)
except ZeroDivisionError:
pass

无显示结果

四、存储数据

1、写入数据

import json
number=[2,3,5,7,11,13]
filename='../data/number.json'
with open(filename,'w') as f:
json.dump(number,f)

查看结果(number.json)

[2, 3, 5, 7, 11, 13]

2、读取数据

filename='../data/number.json'
with open(filename) as f:
numbers=json.load(f)
print(numbers)

查看结果:

[2, 3, 5, 7, 11, 13]

3、json+input:保存和读取用户输入

username=input("What is your name?")
filename='username.json'
with open(filename,'w') as f:
json.dump(username,f)
print(f"We'll remember you when you come back,{username}!")
with open(filename) as f:
username=json.load(f)
print(f"Welcom back,{username}")

查看结果:

What is your name?mike
We'll remember you when you come back,mike!
Welcom back,mike

4、封装用户输入与存储

def get_stored_username():
"""当没有错误时读取保存的用户名"""
filename='username.json'
try:
with open(filename) as f:
username=json.load(f)
except FileNotFoundError:
return None
else:
return username

def get_new_username():
"""验证新用户名"""
username=input("What is your name?")
filename='username.json'
with open(filename,'w') as f:
json.dump(username,f)
return username

def greet_user():
"""greet the user by name"""
username=get_stored_username()
if username:
print(f"Welcome back,{username}!")
else:
username=get_new_username()
print(f"We will remember you when you come back,{username}!")

greet_user()

查看运行结果:

Welcome back,mike!