Python学习10

"""

第10章  文件和异常

    xx.read()
    xx.readlines()
    ZeroDivisionError 异常
    FileNotFoundError异常
    try-except 代码块
    pass

"""


# 10.1  读取文件 
"""
新建pi_digits.txt

3.1415926535
  8979323846
  2643383279
  
  保存至此py同文件夹
"""

with open('pi_digits.txt') as file_object:   # python只在python_work中查找文件,不在其子目录查找
    """函数open接受一个参数:文件名,返回一个表示文件的对象"""
    contents = file_object.read()
    print(contents)
    
"""
输出结果很有可能多出一个空行
read到达文件末尾时返回一个空字符串,显示出来就是一个空行
要删除末尾行,可使用rstrip(),即:
print(contents.rstrip())
"""

"""
这里使用了 open() 但未使用 close()
若都使用,如果程序存在bug,导致close()未执行,文件将不会关闭,可能导致文件丢失或受损。
如果过早调用close(),可能使用时已关闭,会导致更多错误。
因而只管打开文件,Python能根据前面的结构,在需要时使用它,在合适的时候自动将其关闭
"""

with open('file_testing\pi.txt') as file_object2:   # 在python_work子目录中查找
    contents = file_object2.read()
    print(contents)

file_path = 'D:\AppStore\matlab2018a\pi.txt'        # 其他目录
with open(file_path) as file_object3:
    contents = file_object3.read()
    print(contents)


# 10.1.3  逐行读取

filename = 'pi_digits.txt'

with open(filename) as file_object:
    for line in file_object:
        print(line)
"""
逐行读取每一行结束都会有一个空行
因为文件中每行末尾都有一个看不见的换行符
而print语句也会加上一个换行符,因此有两个
消除空行依旧使用:
    print(line.rstrip())
"""


# 10.1.4  创建一个包含文件各行内容的列表

filename = 'pi_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()     # readlines() 读取每一行,并存储在一个列表中
    # 此处若是把 readlines 换成 read 打印结果将是 3.1415926 纵向
    
print(lines)
"""
['3.1415926535\n', '  8979323846\n', '  2643383279']
"""
for line in lines:
    print(line.rstrip())                # lines每个元素对应文件中的一行
"""
3.1415926535
  8979323846
  2643383279
"""



# 10.1.5 使用文件的内容

filename = 'pi_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines() 

pi_string = ''
pi_string2 = ''
for line in lines:
    pi_string += line.rstrip()  # 删除末尾换行符
    pi_string2 += line.strip()  # 删除所有空格

print(pi_string)
print(len(pi_string))
print(pi_string2)
print(len(pi_string2))
"""
3.1415926535  8979323846  2643383279
36
3.141592653589793238462643383279
32
"""

"""
读取文本时,Python将所有文本都解读为字符串,若作为数字就要使用int()  or  float()
"""



# 10.1.6 包含一百万位的大文件(举例只有几百位)
filename = 'pi01.txt'

with open(filename) as file_object:
    lines = file_object.readlines() 

pi_string = ''
for line in lines:
    pi_string += line.strip()   # 删除所有空格

print(pi_string[:52] + "...")   # 只打印前52位
print(len(pi_string))


birthday = input("Enter your birthday:")

if birthday in pi_string:
    """圆周率中包含你的生日吗"""
    print("Your birthday appears in the pi.")
else:
    print("Your birthday does not appear in the pi.")



# 10.2  写入文件

filename = 'po.txt'                             # 存在po直接调用,不存在,则open()会新建

with open(filename,'w') as file_object:         # w 写入空文件
    file_object.write("I love programming.")
    file_object.write("That's a joke.")
"""po.txt
I love programming.That's a joke.  写入内容在一行
"""
with open(filename,'w') as file_object:     
    file_object.write("I love programming.\n")
    file_object.write("That's a joke.\n")       # 若要换行则要\n

with open(filename,'a') as file_object:         # a 附加到文件
    file_object.write("He love programming.\n")
    file_object.write("That's a joke too.\n") 



# 10.3  异常
"""
Python使用被称为异常的特殊对象来管理程序执行期间的错误。
每当程序发生错误,会创建一个异常对象。如果编写了处理该异常的代码,程序将继续运行。
未对异常进行处理,程序将停止,并显示一个traceback,其中包含有关异常的报告。

异常是使用try-except代码块处理的。try-except让Python执行指定操作。
"""

    
# 10.3.1 处理 ZeroDivisionError 异常

print(5/0)

"""
Traceback (most recent call last):
  File "D:\python_work\practice22.py", line 12, in 
    print(5/0)
ZeroDivisionError: division by zero  ①
"""
# ①处指出的错误ZeroDivisionError是一个异常对象



# 10.3.2  使用 try-except 代码块
try:
    print(5/0)                          # 将代码放在try模块中,如果运行没问题则跳过except代码块
except ZeroDivisionError:
    print("You can't divide by zero!")


    
# 10.3.3  使用异常避免崩溃
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 can't divide by zero!")
    else:
        print(answer)



# 10.3.5  处理FileNotFoundError异常
filename = 'alice.txt'
with open(filename) as f_obj:
    contents = f_obj.read()
    print(contents)
"""
Traceback (most recent call last):
  File "D:\python_work\practice22.py", line 5, in 
    with open(filename) as f_obj:
FileNotFoundError: [Errno 2] No such file or directory: 'alice.txt'
"""


filename = 'alice.txt'
try:
    with open(filename) as f_obj:
        contents = f_obj.read()
        print(contents)
except FileNotFoundError:
        msg = "Sorry,the file " + filename + " does not exist."
        print(msg)



# 10.3.6  分析文本

title = 'Alice in wonderland'
print(title.split())            # ->  ['Alice', 'in', 'wonderland']
# 方法split()以空格为分隔字符拆分成多个部分,并将这些部分存储到一个列表中


filename = 'aa.txt'

try:
    with open(filename) as obj:
        contents = obj.read()
except FileNotFoundError:
    msg = "Sorry, the file " + filename + " does not exit"
    print(msg)
else:
    # 计算文件大致包含多少个单词
    words = contents.split()        
    num_words = len(words)
    print("The file " + filename + " has about " + str(num_words) + " words.")



# 10.3.7  使用多个文件
def count_words(filename):
    """计算一个文件大致包含多少个单词"""
    try:
        with open(filename) as obj:
            contents = obj.read()
    except FileNotFoundError:
        msg = "Sorry,the file " + filename + " does not exit ."
        print(msg)              
        """
        except FileNotFoundError:   # ②使用 pass 替换  msg...  和 print(msg)
            pass
        """
    else:
        # 计算文件大致包含多少个单词
        words = contents.split()
        num_words = len(words)
        print("The file " + filename + " has about " + str(num_words) + " words.")

filename = 'alice.txt'
count_words(filename)

filenames = ['aa.txt','bb.txt','cc.txt']   # 打开多个文件
for filename in filenames:
    count_words(filename)
"""
Sorry,the file alice.txt does not exit .
The file aa.txt has about 18 words.
Sorry,the file bb.txt does not exit .
Sorry,the file cc.txt does not exit .
"""

# 10.3.8  失败时一声不吭
# 使用  pass  异常时,什么都不发生,不会出现traceback,也没有输出
"""代码修改见②,运行结果如下
Sorry,the file alice.txt does not exit .
The file aa.txt has about 18 words.
"""

# 10.4.1  json.dump() 和 json.load()

import json

numbers = [2,3,5,7,11,13]

filename = 'numbers.json'
with open(filename,'w') as f_obj:
    json.dump(numbers,f_obj)            # 存储到文件numbers.json

with open(filename) as f_obj:
    numbers = json.load(f_obj)          # json.load加载存储在numbers.json中得信息

print(numbers)




# 10.4.2  保存和读取用户生成得数据

import json

username = input("What's your name ?")

filename = 'username.json'
with open(filename,'w') as f_obj:
    json.dump(username,f_obj)           # 存储
    print("We will remember you when you come back," + username)
    
with open(filename) as obj:
    username = json.load(obj)           # 加载信息
    print("Welcome back," + username)



import json
# 如果以前存储了用户名,就加载它
# 否则,就提示用户输入用户名并存储它
filename = 'username.json'
try:
    with open(filename) as f_obj:
        username = json.load(f_obj)
except FileNotFoundError:
    username = input("What's your name?")
    with open(filename,'w') as f_obj:
        jsondump(username,f_obj)
        print("We'll remember you when you come back," + username)
else:
    print("Welcome back" + username)


# 10.4.3  重构:代码能正确运行,但可做进一步改进——将代码划分为一系列具体工作的函数。

import json

def greet_user():
    """问候用户,并指出其名字"""
    filename = 'username.json'
    try:
        with open(filename) as f_obj:           # 判断文件是否存在,存在则执行else输出结果
            username = json.load(f_obj)
    except FileNotFoundError:
        username = input("What's your name?")   # 不存在则输入名字,并输出
        with open(filename,'w') as f_obj:
            json.dump(username,f_obj)
            print("We'll remember you when you come back," + username)
    else:
        print("Welcome back," + username)

greet_user()


            
# 重构1 ⬇  将[判断文件是否存在]与[输入输出部分]分成两个函数
import json

def get_stored_username():                  # 判断文件是否存在,存在返回username  不存在返回None
    """如果存储了用户名,就获取他"""
    filename = 'username.json'
    try:
        with open(filename) as f_obj:
            username = json.load(f_obj)
    except FileNotFoundError:
        return None
    else:
        return username

def greet_user():
    """问候用户,并指出其名字"""
    username = get_stored_username()        # 调用get...函数
    if username:
        print("Welcome back," + username)
    else:
        username = input("What's your name?")
        filename = 'username.json'
        with open(filename) as f_obj:
            json.dump(username,f_obj)
            print("We'll remember you when you come back," + username)

greet_user()



            
# 重构2 ⬇  [判断文件是否存在]  [输入]  [输出]三个函数
import json

def get_stored_username():                  # 判断文件是否存在,存在返回username  不存在返回None
    """如果存储了用户名,就获取他"""
    --snip--

def get_new_username():
    """提示用户输入用户名"""
    username = input("What's your name?")
    filename = 'username.json'
    with open(filename) as  f_obj:
        json.dump(username,f_obj)
    return username

def greet_user():
    """问候用户,并指出名字"""
    username = get_stored_username()
    if username:
        print("Welcome back," + username)
    else:
        username = get_new_username()
        print("We'll remember you when you come back," + username)

greet_user()

你可能感兴趣的:(Python)