读取、写入文件 、存储数据

1、读取文件json

一、读取整个文件ide

file_name = 'cat.txt'spa

with open(file_name) as file_object:ip

  contents = file_object.read()input

 print(contents) string

二、逐行读取,可以使用for循环it

file_name = 'cat.txt'for循环

with open(file_name) as file_object:import

  for line in file_object:重构

    print(line.rstrip())

三、建立一个包含文件各行内容的列表

file_name = 'cat.txt'

with open(file_name) as file_object:

  lines = file_object.readlines()

for line in lines:

  print(line.rstrip())

四、使用文件的内容

file_name ='pi.txt'

with open(file_name) as file_object:

  lines = file_object.readlines()

pi_string = ' '

for line in lines:

  pi_string += line

print(pi_string)

2、写入文件

一、‘w’写入

with open(filename,'w') as file_object:

  file_object.write(I want to hide")

注:写入多行时后面须要加换行符。

二、‘a'附加  

with open(filename,'a') as file_object:

  file_object.write('I want to sleep')

3、异常

try-except-else

else在try代码块中执行成功时运行else代码块。

4、存储数据

一、json.dump() 接受两个实参,要存储的数据,以及要存储数据的文件类型

   json.load()接受一个实参,文件类型

二、如何用json.dump()来存储列表

import json

numbers = [1,2,3,4,5,6]

filename = number.josn

with open(filename,'w') as file_object:

  josn.dump(numbers,file_object)

三、保存和读取用户生成的数据

import json
file_name = 'number.json'
try:
with open(file_name) as file_object:
fav_number = json.load(file_object)

except:
number = input("请输入你喜欢的数字:")
with open(file_name,'w') as file_object:
fav_number = json.dump(number,file_object)
else:
print("您最喜欢的数字是:%s" % fav_number)

四、重构

import json
file_name = 'username.json'
def got_name():
"""获取用户名称"""
try:
with open(file_name) as file_object:
user_name = json.load(file_object)
except:
return None
else:
return user_name

def new_name():
"""提醒用户输入名字"""
user_name = input("请输入您的名字:")
with open(file_name,'w') as file_object:
put_name = json.dump(user_name,file_object)
return user_name


def greet():
"""向用户发出问候"""
username = got_name()
if username:
ask = input("用户名是%s吗?"%username)
if ask == 'y':
print("欢迎回来%s"%username)
else:
user_name =new_name()
print("下次我会记得你哦!%s"%user_name)
else:
user_name = new_name()
print("下次我会记得你哦!%s" % user_name)
greet()
相关文章
相关标签/搜索