1.读文件
查看文件需要先打开再查看或者执行其他动作。
open函数接收的参数就是要打开的文件,python会在当前程序所在的位置寻找该文件,如果这个文件存放在其他位置则报错。
关键字with表示执行操作后关闭文件。也可以使用close关闭,但是如果发生错误没有执行close可能会损坏文件。
read方法读取文件内容并转化为字符串。read到达文件末尾时会返回空字符串
rstrip方法可以去空
with open('a.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
如果要使用的文件在程序目录下,那么可以使用相对路径。如果要使用的文件在其他目录,那么使用绝对路径。在linux环境下使用斜杠,windows环境使用反斜杠。可以把路径存放在一个变量,通过变量寻找。
with open('files\a.txt') as file_object:
with open('C:\files\a.txt') as file_object:
逐行输出
with open('a.txt') as file_object:
for contents in file_object:
print(contents.rstrip())
注意以上例子open返回的文件对象只能在with里使用,如果需要在其他地方使用则需要将文件内容储存到列表等。可以使用readlines方法逐行读取文件内容并储存到链表,接着使用for循环即可逐行输出。
with open('a.txt') as file_object:
contents = file_object.readlines()
for line in contents:
print(line.rstrip())
可以将内容输出为连续的字符串
with open('a.txt') as file_object:
contents = file_object.readlines()
line_string = ''
for line in contents:
line_string +=line.strip() #使用strip删除空格
print(line_string[:10]+"...") #限制输出长度
print(len(line_string)) #使用len计算字符串长度
可以进行字符串匹配,输入生日和圆周率进行匹配判断是否包含生日。
with open('a.txt') as file_object:
contents = file_object.readlines()
line_string = ''
for line in contents:
line_string +=line.strip() #使用strip删除空格
bir=input("enter you birthday,in the form yymmdd:")
if bir in line_string:
print("OHOHOHOH")
else:
print("sorry")
2.写文件
实际上,调用open时应该传入两个参数,一个文件路径,另一个是执行方式。执行方式有r(读),w(写),读写(r+),a(附加),默认是r。
使用write写的时候同样有限制,只能写入字符串。并且写入的内容将覆盖原本的内容,比较适合写空文件。
with open('a.txt','w') as file_object:
file_object.write("hello python\n")
file_object.write("hello world\n")
可以使用附加在原本内容的基础上进行增添。
with open('a.txt','a') as file_object:
file_object.write("hello python\n")
file_object.write("hello world\n")
3.储存数据
有一种使用简单用途广泛的储存方式,json。
使用json.dump可以将数据储存到json文件,json.load可以提取数据到内存。
import json #导入模块json
numbers = [2,4,6,8,10]
filename = 'numbers.json' #指定储存文件
with open(filename,'a') as file_object: #写入模式打开文件并写入
json.dump(numbers,file_object) #使用函数json.dump将列表储存到文件
import json #导入模块json
with open('numbers.json') as f_obj:
numbers = json.load(f_obj)
print(numbers)
可以将以上两个程序合并,使用异常作为处理首次运行程序时文件不存在的情况。
import json #导入模块json
filename = 'username.json'
#如果已经储存了用户名就加载,否则输入并储存
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input("enter you name:")
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print(username)
else:
print("wecome "+username)
还可以使用重构将功能分离
import json #导入模块json
def get_name():
#如果已经储存了用户名就加载
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
def greet_user():
#说出用户姓名
username =get_name()
if username:
print("wecome "+username)
else:
username = get_newname()
print("remember name is "+username)
def get_newname():
#输入用户名
username = input("enter you name: ")
filename = 'username.json'
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
return username
greet_user()