Python----文件和异常-创新互联

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

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


当前标题:Python----文件和异常-创新互联
地址分享:http://pwwzsj.com/article/djcipg.html