一文看懂Python文件的读取写入操作,建议收藏-bak文件怎么打开

文件的读取写入操作

读取文件read()

假设我们有一个与操作文件同级的1.txt文档

with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)

逐行读取

with open('pi_digits.txt') as file_object:
for line in dile_object:
print(line, end='')

# rstrip()删除末尾多余空白行
with open('1.txt') as objfile:
for line in objfile:
print(line.rstrip())

# 逐行读取
with open('1.txt') as objfile:
lines = objfile.readlines()
for line in lines:
print(line.rstrip())

# 利用文件内容:
with open('E:/python/pythbj/数据库/1.txt') as objfile:
lines = objfile.readlines()
pi_string = ''
for line in lines:
pi_string += line.rstrip()
print(pi_string)
print(len(pi_string))

写入文件write()

写入模式时open()函数提供两个参数,第一个实参是要打开的文件的名称;第二个实参要以那种模式写入并打开这个文件,如果写入的数据包含中文需在open()函数中定义encoding='utf_8'

案例:

file = "1.txt"
with open(file, 'w' encoding='utf_8') as objfile:
objfile.write("这是我用w模式写入到1.txt文件中的语句")

模式解释备注w写入模式如果文件已经存在,在写入前会打开清空以前的数据,再写入r读取模式默认为只读模式打开,可省略a附加模式附加写入在文件末尾r+读取写入读取并写入文件,也会清空原有数据wb二进制模式存储为二进制数据rb读取二进制数据相对用于wb存储的数据

存储数据

使用json模块存储数据

JSON(JavaScript Object Notation)格式最初是为JavaScript开发的,但随后成了一种常见格式,被包括Python在内的众多语言采用。这让你能够将以JSON格式存储的数据与使用其他编程语言的人分享。这是一种轻便格式,很有用,也易于学习。

#=>使用 json.dump() 存储数据:

import json
names = ['zhangzhen','mayaping', 'zhangyuxi']
file = 'namesfile.json'
with open(file, 'w') as objfile:
json.dump(names, objfile)

备注:函数json.dump() 接受两个实参:要存储的数据以及可用于存储数据的文件对象。

#=> 使用 json.load() 将数据读取到内存中:

import json
file = 'namesfile.json'
with open (file) as objfile:
names = json.load(objfile)
print(names)

综合案例: 创建一个存储用户名的文件,并在打开时提示个性化问候

import json
def get_username():
# 返回用户名
try:
with open(filename) as objfile:
username = json.load(objfile)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
# 创建用户
filename = 'username.json'
username = input("请输入您的用户名:")
with open(filename, 'a') as objfile:
json.dump(username, objfile)
return username

def greet_name():
# 如果已经有存储过用户名执行,否则请用户输入
username = get_username()
if username:
print("欢迎回来" + username)
else:
username = get_new_username()
print("We'll remember you when you come back, " + username + "!")
greet_name()

使用pickle模块存储数据

pickle感觉上比较像XML的表示方式,但是,它是Python专用的 方式井且比较容易编写代码。

案例:

import pickle
bob = dict(name='bob', age=35, pay=10000, job='IT')
sue = dict(name='Sue Jones', age=45, pay=30000, job='工程师')
# 字典的字典
db = {}
db['bob'] = bob
db['sue'] = sue
# 存储数据pickle.dump()
with open('dbfile', 'wb') as objfile:
pickle.dump(db, objfile)
# 读取数据pickle.load()
with open('dbfile', 'rb') as objfile:
db = pickle.load(objfile)
db['bob']['pay'] *= 1.25 # 修改数据
for key in db:
print(key)
for name, value in db[key].items():
print(name + '=>' + repr(value)) # repr()内置函数,返回一个对象的string格式
# 存储为.pkl文件
for key, record in [('bob1',bob),('sue1',sue)]:
with open(key + '.pkl', 'wb') as objfile:
pickle.dump(record, objfile)

用glob模块读取整个数据库:

# 读取整个所有后缀为.pkl的文件
import glob
for filename in glob.glob('*.pkl'):
with open(filename, 'rb') as objfile:
record = pickle.load(objfile)
print(filename, '=>', record)

# 读取其中一个文件
with open('bob1.pkl', 'rb') as objfile:
record = pickle.load(objfile)
print(record['name'])

使用shelve模块创建数据

shelve就像一个存储持久化对象的持久化字典。Python会负责处理内容与文件之 间的映射。 shelve模块 的使用方法与 pickle模块 用法类似,只是增加了一个open() 和close() 函数,在win系统下运行会创建多个文件(.bak .dir .dat)[这就是数据库,不能删除]。

# a数据
bob = dict(name='bob', age=35, pay=10000, job='IT')
sue = dict(name='Sue Jones', age=45, pay=30000, job='工程师')
# shelve存储数据
import shelve
db = shelve.open('shelve_file')
# 先修改某一条数据(必须在先)
sue = db['sue']
sue['pay'] *= 1.25
# 存储
db['bob'] = bob
db['sue'] = sue
db.close()
# shelve读取数据
db = shelve.open('shelve_file')
for key in db:
print(key, '=>\n', db[key])
print(db['sue']['name'])
db.close()

一文看懂Python文件的读取写入操作,建议收藏

推荐阅读