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

一、读取文件

1、读取整个文件

file_name = 'cat.txt'

with open(file_name) as file_object:

  contents = file_object.read()

 print(contents) 

2、逐行读取,可使用for循环

file_name = 'cat.txt'

with open(file_name) as file_object:

  for line in file_object:

    print(line.rstrip())

3、创建一个包含文件各行内容的列表

file_name = 'cat.txt'

with open(file_name) as file_object:

  lines = file_object.readlines()

for line in lines:

  print(line.rstrip())

4、使用文件的内容

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)

二、写入文件

1、‘w’写入

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

  file_object.write(I want to hide")

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

2、‘a'附加  

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

  file_object.write('I want to sleep')

三、异常

try-except-else

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

四、存储数据

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

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

2、如何用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)

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

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)

4、重构

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()
在任何时候去学习都不晚,永远不要放弃自己!人生就是一个不断去学习的过程,任何时候,只要你想学,Come on !
原文地址:https://www.cnblogs.com/startingpoint-fly/p/10655922.html