Python----文件和异常
admin
2023-07-16 15:42:45
0

1.从文件中读取数据

#从文件中读取数据

with open("pi_digits.txt") as file_abnormal: #open()函数:接受的参数是要打开文件的名称,在当前目录查找指定文件
contents = file_abnormal.read() #方法read():读取文件的全部内容,到达文件末尾时返回一个空字符
print(contents)
print(contents.rstrip())
print(contents)
#文件路径
#要让Python打开不与程序文件位于同一目录中的文件,需要提供文件路径
#相对路径行不通就使用绝对路径

file_path = r'C:\WiFi_log.txt' #绝对路径,不能含中文
with open(file_path) as file_abnormal:
test = file_abnormal.read()
print(test)
#逐行读取
#检查其中的每一行

filename = 'pi_digits.txt'
with open(filename) as file_object: #使用关键字with时,open()返回的文件对象只在with代码块内可用
lines = file_object.readlines() #将文件各行存储在一个列表中,只能在with码块外使用
#for line in file_object:
#print(line)
#print(file_object) #只是文件属性?
#print(line.rstrip())
for lin in lines:
print(lin.rstrip())
print("\n")
#使用文件内容
pi_string = " "
for line in lines: #读取文本文件时,Python将所有文本解读为字符串
pi_string += line.strip() #strip():删除空格
#pi_string += line.rstrip() #rstrip():清除空白行
print(pi_string)
print(len(pi_string))
print(pi_string[:52])
print("\n")

Python----文件和异常

2.#写入文件

filenames = 'programming.txt' #创建文件名
with open(filenames,'w') as file_object: #w:写入模式
file_object.write("I love programming.\n") #文件对象方法write()将一个字符串写入文件
file_object.write("I love creating new games.\n")
with open(filenames,'a') as file_object: #'a':附加模式把文件内容附加到文件末尾,而不是覆盖内容
file_object.write("I love creating apps that can run in browser.")

Python----文件和异常

3.存储数据

import json #json模块能将简单的Python数据结构存储到文件中
def greet_user():
filename = 'username.json' #创建文件
try:
with open(filename) as f_log: #注意冒号,打开文件
username = json.load(f_log) #把文件内容加载到变量
except FileNotFoundError:
username = input("What is your name? ") #之前没写入则执行except
with open(filename,'w') as f_log: #写入模式
json.dump(username,f_log) #json.dump进去
print("We'll remember your when you come back, " + username + "!")
else:
print("Welcome back , " + username +"!")
greet_user()
#重构
#代码可以正确的运行,但是可以将代码分为一系列函数来完成

def get_stored_username():
filename = 'username.json'
try:
with open(filename) as f_log:
username = json.load(f_log)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
filename = "username.json"
with open(filename,'w') as f_log:
username = input("What is your name? ")
json.dump(username,f_log)
return username
def new_greet_user():
username = get_stored_username()
if username:
print("Welcome back, " + username + '!')
else:
username = get_new_username()
print("We will remember you when you come back, " + username + '!')
#new_greet_user()
get_new_username()
new_greet_user()

Python----文件和异常

4.异常

#处理ZeroDivisionError异常
#print(5/0)

print("\n")
#使用异常避免崩溃
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("\nSecond number: ")
#if second_number == 'q':
#break
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You don't divide by 0!")

else:
    print(answer)

#处理FileNotFoundError异常
#filename = 'init.txt'

try:
with open(filename) as log_object:
contents = log_object.read()
except FileNotFoundError: #避免客户或者*看到异常
print("\nSorry,the file "+ filename + "done't exit.")
else:
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
#使用多个文件
def count_words(filename): #定义函数注意加形参
try:
with open(filename) as log_object:
contents = log_object.read()
except FileNotFoundError: * # 避免客户或者
看到异常**
print("\nSorry,the file " + filename + "done't exit.")
else:
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
filename = 'programming.txt'
count_words(filename)
print("\n")
Python----文件和异常

def count_words(filename):
try:
with open(filename) as log_object:
contents = log_object.read()
except FileNotFoundError: **# 避免客户或者*看到异常
#print("\nSorry,the file " + filename + "done't exit.")
pass #失败时一声不吭,让程序继续运行
else:
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
filename = 'programming.txt'
count_words(filename)
filename = ['programming.txt','pi_digits.txt','abc.txt']
for file in filename: #遍历列表传递实参
count_words(file)

Python----文件和异常

相关内容

热门资讯

美媒:拜登家族不肯消失,民主党... 美国将于今年年底举行中期选举,民主党人有望夺回众议院。然而拜登家族的高调举动,使得民主党再次分心,一...
对日本新型军国主义的“新型抗战... 【文/观察者网专栏作者 江宇舟】日本这几个月的对华行为,已经是全方位的恶声、恶气、恶行、恶法:自卫队...
“这里没有口号,只有实干”——... 在黄河科技学院,有这样一个地方:没有惊天动地的口号,没有花里胡哨的“形象工程”,有的只是实验室里彻夜...
AI决定6G成败关键? 专家称... 中经记者 陈佳岚 广州报道 “6G与AI的增强融合,这部分OPPO是全力投入的。而与AI的融合,也是...
自贡:“智造”为核,无人车跑出... 盐都初夏清晨,和勤劳的人们一同早起的,还有一辆辆造型新颖的无人配送车、清扫作业车。市民杨先生对此颇有...
黄仁勋不装了:所有芯片市场我全... 来源:市场资讯 (来源:科技头版) 英伟达要当AI时代唯一的王。 出品 | 科技头版 作者 | 青...
Ducky展出平价磁轴键盘OK... IT之家 6 月 3 日消息,键盘品牌 Ducky(吉利鸭)在 COMPUTEX 2026 上带来了...
从工具到底座:私有化即时通讯如... 随着企业数字化建设从单点应用走向整体架构,即时通讯系统的角色正在发生根本性转变——它不再只是一个员工...
运行超11年后失联,NASA正... 【文/观察者网 陈思佳】 当地时间6月3日,美国国家航空航天局(NASA)发布消息称,环绕火星运行...
Meta开发者AI模型一再跳票... 来源:环球网 【环球网科技综合报道】6月4日消息,据《华尔街日报》援引知情人士消息报道,Meta已...