Python学习入门之文件读写
读取整个文件
在同一个文件夹中,包含一个pi_digits.txt文件,下面用程序打开并读取这个文件,再将其内容显示在屏幕上
file_name = "pi_digits.txt"
with open(file_name) as file_object: #打开文件并赋值给file_object变量
contents = file_object.read() #读取文件
print(contents)
#函数open()接受一个参数:要打开的文件的名称
#关键字with 在不再需要访问文件后将其关闭,Python自会在合适的时候自动将文件关闭
#Python中使用相对文件路径和绝对文件路径来访问要打开的文件
逐行读取
with open(file_name) as file_object:
for line in file_object:
print(line.rstrip()
创建一个包含文件各行内容的列表
with open(file_name) as file_object:
lines = file_object.readlines()
pi_string = ""
for line in lines:
pi_string +=line.strip()
print(pi_string)
写入文件
保存文件的最简单的方式之一是将其写入到文件中。
写入空文件
要将文本写入文件,在调用open()时需要提供另一个实参,告诉python你要写入打开的文件
file_name = "love.txt"
with open(file_name,"w") as file_object:
file_object.write("I love Lina\n")
file_object.write("But we are impossible\n")
读取模式(r),写入模式(w),附加模式(a),读写模式(r+)
附加到文件
file_name = "love.txt"
with open(file_name,"a") as file_object:
file_object.write("Because she doesn't like me anymore")
存储数据
使用json.dump()和json.load()
函数json.dump()接受两个实参,要存储的数据以及可用于存储数据的文件对象
import json
number = [1,2,3,4,5,6,7,8,9]
filename = "number.json"
with open(filename,"w") as f_obj:
json.dump(number,f_obj)
函数json.load()接受一个实参,要读取的文件对象
with open(filename) as f_obj:
nums = json.load(f_obj)
print(nums)
异常处理
当认为可能发生错误时,可编写一个try-except-else来处理可能引发的异常
import json
fileName = "username.json"
try:
with open(fileName) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input("please input your name:")
with open(fileName,"w") as f_obj:
json.dump(username,f_obj)
print("we'll remember you when you comg back, " + username + "!")
else:
print("Welcome back, " + username + "!")