一、读取文件

【注意】

  • 显示文本路径时,Windows系统使用反斜杠(\)而不是斜杠(/),但在代码中依然可以使用斜杠
  • 如果在文件路径中直接使用反斜杠会出现错误,因为反斜杠对于某些字符会进行转义,如\t,\n等。若一定要使用反斜杠,则应对每个反斜杠进行转义如C:\\path\\file.txt

words.txt:

In Python you can add a list
In Python you can add a tuple
In Python you can search a word in a string
In Python you can delete the empty in a string

1)整个文件读取——xxx.read()

with open("words.txt") as file:
    words=file.read()
print(words)
#执行结果
In Python you can add a list
In Python you can add a tuple
In Python you can search a word in a string
In Python you can delete the empty in a string

2)逐行读取——利用循环for

with open("words.txt") as file:
    for full in file:
        print(full.strip())
#执行结果
In Python you can add a list
In Python you can add a tuple
In Python you can search a word in a string
In Python you can delete the empty in a string

3)创建一个包含文件各行的列表——xxx.readlines()

with open("words.txt") as file:
    lines=file.readlines()
for line in lines:
    print(line.strip())
#执行结果
In Python you can add a list
In Python you can add a tuple
In Python you can search a word in a string
In Python you can delete the empty in a string

二、写入文件

在打开文件的时候,可以对文件进行选择一个模式:

参数

模式

r

读取模式,可读取文件信息。

w

写入模式,若文件未存在,则创建文件;若已存在则清空原文件

a

附加模式,若文件未存在,则创建文件;若已存在则在原文件末尾附加字符串

r+

读写模式,可对文件进行读和写操作。会在当前文件指针位置写入

使用xxx.write()写入文件

还是使用上面的words.txt:作为例子:

1.使用w模式打开

with open("words.txt",'w') as file:
    words="Hello!"
    file.write(words)
#文件内容
Hello!

2.使用a模式打开

with open("words.txt",'a') as file:
    words="Hello!"
    file.write(words)
#文件内容
In Python you can add a list
In Python you can add a tuple
In Python you can search a word in a string
In Python you can delete the empty in a stringHello!

3.使用r+模式打开

with open("words.txt",'r+') as file:
    words="Hello!"
    file.write(words)
#文件内容
Hello!hon you can add a list
In Python you can add a tuple
In Python you can search a word in a string
In Python you can delete the empty in a string

三、异常

Python使用称为异常的特殊对象来管理程序执行期间发生的错误。

下面来看一个错误的程序

num=5/0

执行结果:

python斜杠报错 python斜杠t_json

在上面的Traceback中最后一行,可以看到有一个异常对象ZeroDivisionError,它会指出你犯了哪种类型的错误,以及如何错误的使用了一些代码或值

四、处理异常

1)使用try-except代码块

很多时候,错误的执行结果很容易暴露出我们程序中的一些属性和属性名称,这样是很不安全的。

因此我们会使用try-except代码块,让程序在出现异常时执行我们想要它执行的结果,同时还可以避免程序崩溃。

try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")
#执行结果
#You can't divide by zero!

在try程序中执行的代码如果出现了异常,会转到except块中对应异常信息的处理,执行你想要的代码。

2)else代码

try:
    num=5/2
except ZeroDivisionError:
    print("You can't divide by zero!")
else:
    print(num)
#执行结果
#2.5

如果try代码块中没有出现异常,那么程序就会跳转到else代码块

3)静默失败

可以在except代码块中使用passz静默失败,让程序在出现异常时保持静默。pass是一个占位符,什么都不做。

try:
    num=5/0
except ZeroDivisionError:
    pass
else:
    print(num)
print("End!")
#执行结果
#End!

五、存储数据

很多时候我们会要就把一些数据存储到文件当中,这时候通常会用到json文件,json格式存储的数据可以与使用其他编程语言的人分享。

使用json需要导入json模块

import json

import json
def get_stored_username():
    """如果存在这个文件,获取里面的用户名"""
    filename='Test10-13.json'
    try:
        with open(filename) as file:
            username=json.load(file)
    except FileNotFoundError:
        return None
    else:
        return username

def get_new_username():
    """获取新的用户名,存储到一个文件中"""
    username=input("What is your name?")
    filename='Test10-13.json'
    with open(filename,'w') as file:
        json.dump(username,file)
    print(f"We'll rember you when you come back,{username}!")

def confirm_username(username):
    """确认当前的用户是否为文件中的用户"""
    res=input(f"Is it '{username}' your username?Press Y or N:")
    if res.lower()=='y':
        print(f"Welcome back,{username}!")
    elif res.lower()=='n':
        get_new_username()

def greet_user():
    """问候用户"""
    username=get_stored_username()
    if username:
        confirm_username(username)
    else:
        get_new_username()

greet_user()

1)json.dump()——存储数据到json文件当中

接受两个参数,第一个是要存储的数据,第二个参数是用于存储的文件对象

2)json.load()——读取文件中的数据到程序中

接受一个参数:用于读取数据的文件对象;会返回读取到的数据