当前位置:   article > 正文

python学习笔记———文件和异常

python学习笔记———文件和异常
  1. 函数open()

函数open()第一个参数是要打开的文件的名称。Python 在当前执行的文件所在的目录中查找指定的文件,并返回一个表示文件的对象。第二个参数可指定读取模式(‘r’)、写入模式(‘w’)、附加模式(‘a’)或读写模式(‘r+’),若省略模式实参,则默认只读模式打开文件。第三个参数是指定返回的数据采用何种编码,一般采用utf-8或gbk,也可不写。

以写入模式打开文件时,若文件不存在,则函数open()将自动创建一个空文件。若指定的文件已经存在,Python 将在返回文件对象前清空文件的内容。

以附加模式打开文件,若文件不存在,则函数open()将自动创建一个空文件。Python不会再返回文件对象前清空文件的内容,而是将写入文件的行添加到文件末尾。

  1. 从文件中读取数据

关键字with 在不需要访问文件后将其关闭
函数read()读取文件的全部内容,并将其作为一个长长的字符串赋给contents。read()到达文件末尾时会返回一个空字符串,要删除多出来的空行,可以使用rstrip()

with open('pi_digits.txt') as file_object:
    contents = file_object.read()
print(contents.rstrip())
  • 1
  • 2
  • 3

使用相对路径访问指定文件

#访问当前运行的程序所在目录下的text_files文件里的filename.txt
with open('text_files/filename.txt') as file_object:
  • 1
  • 2

使用绝对路径访问指定文件

file_path = '/home/ehmatthes/other_files/text_files/_fileName_.txt'
whith open(file_path) as file_object:
  • 1
  • 2

注意:在文件路径中应使用斜杆“/”,若使用反斜杆,要对路径中的每个反斜杆都进行转义,如"C:\\path\\to\\file.txt"。

逐行读取文件

with open('pi_digits.txt') as file_object:
    for line in file_object:
        print(line.rstrip())
  • 1
  • 2
  • 3

创建一个包含文件各行内容的列表
readlines()从文件中读取每一行,并将其存储在一个列表中

with open('pi_digits.txt') as file_object:
    lines = file_object.readlines()
for line in lines:
    print(line.rstrip())
  • 1
  • 2
  • 3
  • 4
  1. 写入文件

写入空文件,覆盖原有的内容

#写入单行
with open('programming.txt', 'w') as file_object:
    file_object.write("I love programming")

#写入多行
with open('programming.txt', 'w') as file_object:
    file_object.write("I love programming\n")
    file_object.write("I love creating new games.\n")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

给文件添加内容,不覆盖原有的内容

with open('programming.txt', 'a') as file_object:
    file_object.write("I love programming\n")
    file_object.write("I love creating new games.\n")
  • 1
  • 2
  • 3
  1. 异常

try-except-else代码块
将可能发生异常的代码放到try语句中。将发生异常后要如何处理的代码放到except语句中。将依赖try代码块成功执行的代码都放到else语句中。如果try代码块中的代码运行起来没有问题,Python将跳过except代码块,执行else代码块。如果try代码块中的代码导致了错误,Python将查找与之匹配的except语句并运行其中的代码。

#计算文件中的单词数,若触发找不到文件的Error,则向用户提示
filenmea = 'alice.txt'
try:
    with open(filename, encoding='utf-8') as f:
        contents = f.read()
except FileNotFoundError:
    print(f"Sorry, the file {filename} does not exist.")
else:
    words = contents.split()
    num_words = len(words)
    print(f"The file {filename} has about {num_words} words.")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

函数split()以空格为分隔符将字符串分拆成多个部分,并将这些部分存储到一个列表中。

  1. 使用json存储数据

函数json.dump()接受两个参数,第一个参数是要存储的数据,第二个参数是用于存储数据的文件对象。
函数json.load()接受一个参数,指明需要读取数据的的文件对象。读取存储在文件中的信息。

import json

filename = 'username.json'
try:
    with open(filename) as f:
        username = json.load(f)
except FileNotFoundError:
    username = input("What is your name?")
    with open(filename, 'w') as f:
        json.dump(username, f)
        print(f"We'll remember you when you come back, {username}!")
else:
    print(f"Welcome back, {username}!")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号