温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python----文件和异常

发布时间:2020-07-25 09:26:11 来源:网络 阅读:555 作者:bigbeatwu 栏目:编程语言

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问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI