我们专注攀枝花网站设计 攀枝花网站制作 攀枝花网站建设
成都网站建设公司服务热线:400-028-6601

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

Python----文件和异常

1.从文件中读取数据

创新互联建站是一家集做网站、成都网站制作、网站页面设计、网站优化SEO优化为一体的专业网站设计公司,已为成都等多地近百家企业提供网站建设服务。追求良好的浏览体验,以探求精品塑造与理念升华,设计最适合用户的网站页面。 合作只是第一步,服务才是根本,我们始终坚持讲诚信,负责任的原则,为您进行细心、贴心、认真的服务,与众多客户在蓬勃发展的市场环境中,互促共生。

#从文件中读取数据

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----文件和异常


分享名称:Python----文件和异常
链接分享:http://mswzjz.cn/article/gedisp.html

其他资讯