1,文件的读取
# 1,读取文件内容并打印
# with open('源代码文件\chapter_10\pi_digits.txt') as fp:
# content = fp.read()
# print(content.rstrip()) #去除空行
# 2,文件路径创建成一个对象
# file_path = 'C:/Users/zxr/Desktop/python文件/源代码文件/chapter_10/pi_digits.txt' #绝对路径/
# with open(file_path) as fp1:
# contents = fp1.read()
# print(contents.rstrip())
# 3,逐行读取
# file_path = 'C:/Users/zxr/Desktop/python文件/源代码文件/chapter_10/pi_digits.txt' #绝对路径/
# with open(file_path) as fp1:
# for line in fp1:
# print(line.rstrip())
# 4,把文件内容存在列表中,文件外也可以用
# file_path = 'C:/Users/zxr/Desktop/python文件/源代码文件/chapter_10/pi_digits.txt' #绝对路径/
# with open(file_path) as fp1:
# lines = fp1.readlines() #每行读出来,存成列表
# # print(lines)
# for line in lines: #从列表中读取数据
# print(line.rstrip())
# 5,三行变成一行
# file_path = 'C:/Users/zxr/Desktop/python文件/源代码文件/chapter_10/pi_digits.txt' #绝对路径/
# with open(file_path) as fp1:
# lines = fp1.readlines() #每行读出来,存成列表
# pi_string = ''
# for line in lines: #取出列表中的每个元素
# pi_string += line.strip() #去除左右空格
# print(pi_string)
# print(len(pi_string))
# # 6,打印小鼠后的52位数字
# file_path = '源代码文件/chapter_10/pi_million_digits.txt' #绝对路径/
# with open(file_path) as fp1:
# lines = fp1.readlines() #每行读出来,存成列表
# pi_string = ''
# for line in lines: #取出列表中的每个元素
# pi_string += line.strip() #去除左右空格
# print(f"{pi_string[:52]}...") #取小数点后52位(切片)
# print(len(pi_string))
# 7,判断生日是否在这个小数12中
file_path = '源代码文件/chapter_10/pi_million_digits.txt' #绝对路径/
with open(file_path) as fp1:
lines = fp1.readlines() #每行读出来,存成列表
pi_string = ''
for line in lines: #取出列表中的每个元素
pi_string += line.strip() #去除左右空格
birthday = input("Enter your birthday,in the form mmddyy:")
if birthday in pi_string:
print("Your birthday appears in the first millon digits of pi!")
else:
print("Your birthday appears not in the first millon digits of pi!")
2,写文件
# 1,保存文档 ’w'
file_path = 'C:/Users/zxr/Desktop/python文件/programming.txt'
with open(file_path,'w') as fp:
fp.write(" trrb bwj ew.\n")
fp.write(" wrcvw wrvcr rwv bvt.\n")
# 2,追加内容 ‘a'
file_path = 'C:/Users/zxr/Desktop/python文件/programming.txt'
with open(file_path,'a') as fp:
fp.write(" 啊读书 .\n")
fp.write(" 日vct率TV 热风.\n")
3,异常处理
# 1,解决异常 try代码执行后,没有异常就会忽略except后面的内容;出现异常并且和指定的异常是相同的,就会执行except后面缩进的代码
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
print(" Give me two number,and I'll divide them. ")
print("Enter 'q' to quit. ")
while True:
first_number = input("\n First number:")
if first_number == 'q':
break
second_number = input("\n Second number:")
if second_number == 'q':
break
try:
answer = int(first_number) / int(second_number) #解决这个代码出现的异常
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print(answer)
# 文件找不到异常
filename = 'alice.txt'
try:
with open(filename,encoding='utf-8') as f:
f.read()
except FileNotFoundError:
print(f"Sorry ,the file {filename} does not exits.")
# # 按照x进行切分成列表
# title = "ewq d3e2 c23cf4"
# print(title.split())
#try一定会执行。不通过就执行except的代码,通过就执行else代码
def count_words(filenamee):
'''计算一个文件大致包含多少个单词'''
try:
with open(filename,encoding='utf-8') as f:
content = f.read()
except FileNotFoundError:
# print(f"Sorry ,the file {filename} does not exits.")
pass #忽略不存在的文件
else:
# 计算文件中包含多少个单词
word = content.split()
num_words = len(word)
print(f"The file {filename} has about {num_words} words")
filenames = ['源代码文件/chapter_10/alice.txt','源代码文件/chapter_10/pi_digits.txt']
for filename in filenames:
count_words(filename)
4,存储数据
# 1,json文件的创建
import json
numbers = [2,4,5,6,8,95]
filename = 'number.json' #创建一个json文件
with open(filename,'w') as f:
json.dump(numbers,f) #保存json数据,要存的数据存在哪里?f中
# 2,json文件的读取
import json
filename = 'number.json' #创建一个json文件
with open(filename) as f:
numbers = json.load(f) #打开文件后,读取内容到numbers变量中
print(numbers)
# 保存和读取用户生成的数据
# 1,把用户输入的名字保存到某个json文件中
# import json
# username = input("What is your name?")
# filename = 'username.json'
# with open(filename,'w') as f:
# json.dump(username,f)
# print(f"We'll remember you when you come back,{username}!")
# 2,向用户打招呼
import json
filename = 'username.json'
with open(filename) as f:
usernames = json.load(f)
print(f"Welcome back,{usernames}")