首页 / PYTHON / Python----文件和异常
Python----文件和异常
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python----文件和异常,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含4874字,纯文字阅读大概需要7分钟。
内容图文
![Python----文件和异常](/upload/InfoBanner/zyjiaocheng/847/82ee2ad5c0e94db7a4ff8f5db4c20e3b.jpg)
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")
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.")
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()
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")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----文件和异常所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。