• Python基础(七)——文件和异常


    1.1 读取整个文件

      我们可以创建一个 test.txt 并写入一些内容,使用 Python 读文件操作,读出文本内容。

    1 with open(r'E:	est.txt') as file_object:
    2     contents = file_object.read()
    3     print(contents.rstrip()) # 可以去除末尾空格(补充:.strip() 去除头尾空格,lstrip() 去除头部空格)
    4     print(file_object)

      解析

      open() 函数:Python 中无论以何种方式使用文件(读取 or 添加等),都需要先 open() 文件。在这里,我们使用 open() 函数打开文件,并将对象存储于 file_object(此对象只能在 with 代码块中使用,如想在with之外用,详见 1.3

      注意:很奇怪,没有 close() 函数,这与 Java 文件操作尤为不同。Python 允许你自己 close ,只是如果你的 close 函数因为异常,而轮不到执行,则文件不会关闭。可能会造成文件数据受损。第二种可能,close 函数过早执行,而后面还有读写操作,则会出现更多错误。幸运的是 Python 可以帮我们找到恰当的关闭时机,并且帮助我们执行关闭操作。    

      以下为输出内容,1~3 行是我的文本内容,最后一行是 file_object 对象:

    1 1.2345
    2    2345
    3    2345
    4 <_io.TextIOWrapper name='E:\test.txt' mode='r' encoding='cp936'>

    1.2 逐行读取

    1 with open(r'E:	est.txt') as file_object:
    2     for line in file_object:
    3         print(line.rstrip())

      注意第三行,如果没有使用 .rstrip() 函数,则输出的每一行之间都有空格。解释:因为在文件中,每行的末尾都有一个看不见的换行符,而 print 函数还会自动加上换行符,所以,一共有两个换行符,使用 .rstrip() 函数可以消除多余的空白行。

      输出:

    1 1.2345
    2    2345
    3    2345

    1.3 存储各行的列表

      由于 1.1 中的 with 的限制,使用 readlines() 可破:

    1 file_content = []
    2 with open(r'E:	est.txt') as file_object:
    3      file_content = file_object.readlines()
    4 
    5 for line in file_content:
    6     print(line.rstrip())

      输出:

    1 1.2345
    2    2345
    3    2345

      如果第三行使用 readline 则只会读取一行,可实验一番。

    2.1 写入空文件

    1 with open(r'E:	est.txt', 'w') as file_object:
    2      file_object.write('aaaasssddd
    dddaass')

      解析

      第一行,依旧使用 open() 函数打开文件(文件不存在则自动创建),传入参数 w,告诉 Python 以 写模式 打开文件(r 读模式,w 写模式,a 附加模式,r+ 读写模式。如果省略,默认读模式)。

      注意:Python 在 w 模式打开文件时,在返回文件对象 file_object 的时候,会清空文件内容。同时, 表示换行,无需写成 \n 或者 r " " 等。write 不会再末尾自动加换行符,需主动加 

    2.2 附加到文件

    1 with open(r'E:	est.txt', 'a') as file_object:
    2      file_object.write('我是附加的内容
    我也是')
    3 
    4 with open(r'E:	est.txt') as file_object2:
    5     content = file_object2.read()
    6     print(content)
    1 aaaasssddd
    2 dddaass我是附加的内容
    3 我也是

    3.1 异常和 try-except-else 代码块

      普通异常处理同 Java 基本一致,如下两个例子:

    1 # 文件异常
    2 try:
    3     with open(r'E:	est3.txt') as file_object2:
    4         content = file_object2.read()
    5 except FileNotFoundError:
    6     print('文件不存在')
    7 else:
    8     print(content)

      try-except-else 代码块工作原理:执行 try 中可能出错的代码快,出错则执行 except ,顺利则执行 else 代码块。

    4.1 os 常用函数补充

    • os.remove(path) 删除一个文件。os.removedir(path) 删除空目录。shutil.rmtree(path) 递归删除整个目录
    • os.getcwd() 查看当前目录
    • os.path.realpath(__file__) 查看当前运行文件路径
    • os.listdir(path) 返回该路径的目录名
    • os.path.exists(path) 判断文件 or 目录是否存在
    • os.path.split(path) 返回路径的目录名和文件名(path可以是文件也可是目录
    • os.path.isdir(path)
    • os.path.isfile(path)
    • os.path.realpath(path) 得到绝对(软连接有效)路径
    • os.path.abspath(path) 得到当前文件绝对路径  与上者区别
    • os.path.splitext(path) 分离文件路径和文件名。如果路径是目录,则后缀为空字符串(path可以是文件也可是目录
    • os.path.basename(path) 返回路径最后一级(path可以是文件也可是目录
    • os.path.dirname(path) 与上一条相反,返回路径目录路径
    • os.path.join(path,file) 连接路径和文件名。类似字符串相加
    • os.chdir(path) 切换路径path不能是是一个文件路径,是目录
     1 import os
     2 import shutil
     3 # print(os.remove(r'E:	est	est.py')) # 删除文件
     4 # print(os.removedirs(r'E:	est')) # 删除空目录
     5 print(shutil.rmtree(r'E:	est')) # 递归删除目录
     6 print(os.getcwd(),  #F:projectsfacialexpress
     7       '	',
     8       os.path.realpath(__file__)) # F:projectsfacialexpress	est.py
     9 
    10 print(os.path.split(r'E:myeclipseCommonartifacts.xml'))
    11 print(os.path.isfile(r'E:myeclipseCommonartifacts.xml'))
    12 print(os.path.isdir(r'E:myeclipseCommonartifacts.xml'))
    13 print(os.path.abspath(os.curdir))
    14 print(os.path.realpath(os.curdir))
    15 print(os.path.splitext(r'E:myeclipseCommonartifacts.xml'))
    16 print(os.path.basename(r'E:myeclipseCommon'))
    17 print(os.path.basename(r'E:myeclipseCommonartifacts.xml'))
    18 print(os.path.dirname(r'E:myeclipseCommonartifacts.xml'))
    19 print(os.path.join(os.getcwd(),'test.py'))
    20 # 以下测试 os.chdir() 切换目录
    21 print('==========','
    ', os.getcwd()) # F:projectsfacialexpress
    22 os.chdir(r'C:Windows')
    23 print('--->',os.getcwd()) # C:Windows
     1 None
     2 F:projectsfacialexpress      F:projectsfacialexpress	est.py
     3 ('E:\myeclipse\Common', 'artifacts.xml')
     4 True
     5 False
     6 F:projectsfacialexpress
     7 F:projectsfacialexpress
     8 ('E:\myeclipse\Common\artifacts', '.xml')
     9 Common
    10 artifacts.xml
    11 E:myeclipseCommon
    12 F:projectsfacialexpress	est.py
    13 ========== 
    14  F:projectsfacialexpress
    15 ---> C:Windows

      

  • 相关阅读:
    实现类似“添加扩展程序…”的设计时支持
    为什么word2007写的文章不能显示在首页
    (翻译)LearnVSXNow!#4 创建一个带有工具窗的Package
    (翻译)LearnVSXNow!#1 如何开始VSX开发?
    测试Windows live writer 发日志
    (翻译)LearnVSXNow!#3 创建一个带有简单命令的Package
    styleSheetTheme和them
    (翻译)LearnVSXNow!#2 创建一个空的VS Package
    VS 2008 Package 备忘
    通用树形表查询SQL
  • 原文地址:https://www.cnblogs.com/KongHuZi/p/11168527.html
Copyright © 2020-2023  润新知