10.1 读取文件
with open(r'D:\\file.txt')as file_object:
contents = file_object.read()
print(contents)
contents.rstrip() 删除字符串末尾的空白
10.2 逐行读取
file_name ='D:\\file.txt'
with open(file_name)as file_object:
for linein file_object:
print(line)
10.3 创建一个包含文件各行内容的列表
file_name ='D:\\file.txt'
with open(file_name)as file_object:
lines = file_object.readlines()
for linein lines:
print(line.rstrip())
10.3.1 使用文件内容
file_name ='D:\\file.txt'
with open(file_name)as file_object:
lines = file_object.readlines()
pi_string =''
for line in lines:
pi_string += line.rstrip()
print(pi_string)
print(len(pi_string)) #打印长度
10.4 写入空文件
file_name ='D:\\file1.txt'
with open(file_name,'w')as file_object:
file_object.write('I love programming \n')
file_object.write('I love programming \n')
10.5 附加到文件
filename ='D:\\file1.txt'
with open(filename,'a')as file_object:
file_object.write("I love creating apps that run in a browser")
10.6 异常
ZeroDivisionError 输入不能为0
while True:
first_number =input("First_number:")
if first_number =='q':
break
second_number =input("Second_number")
if second_number =='q':
break
try:
answer =int(first_number) /int(second_number)
except ZeroDivisionError:
print("you can not divide by 0")
else:
print(answer)
原理:首先会执行 try 代码块中的代码,当尝试运行try 代码块中的代码时引发了指定的异常,执行 except 模块中的代码
10.6.1
FileNotFoundError 文件是否存在
filename ='alice.txt'
try:
with open(filename,encoding='utf-8')as f:
contents = f.read()
except FileNotFoundError:
print(f"sorry,the file {filename} does not exist")
10.6.2 分析文本
filename ='D:\\file3.txt'
try:
with open(filename,encoding='utf-8')as f:
contents = f.read()
except FileNotFoundError:
print(f"sorry,this file {filename} not found")
else:
words = contents.split()
num_words =len(words)
print(f"The file {filename} has about {num_words} words")
输出:
The file D:\file3.txt has about 1 words
10.7 存储数据
#json.dump 写入文件
import json
numbers = [2,3,5,7,9]
filename ='D:\\file4.txt'
with open(filename,'w')as f:
json.dump(numbers,f)
#json.load 读取文件
with open(filename,)as f:
numbers = json.load(f)
print(numbers)
10.7.1保存和读取用户生成的数据
import json
#存储用户姓名 name 到 file4.txt 中
file_name ="D:\\file4.txt"
name =input("请输入姓名:")
with open(file_name,'w')as f:
json.dump(name,f)
#向已存储了名字的用户发出问候
with open(file_name)as f:
name = json.load(f)
print(f"welcome back,{name}")