python文件读写、异常处理

Python进阶----文件读、写

函数open:文件读写,默认读模式
    open(路径文件名.后缀名)
eg:file = open('D:\\tes.txt')
    content = file.read()
    print(content)
    file.close()
读:
read():从文档开始位置读取
readline():读取一行内容,文件指针在哪里就从哪里开始读取一行
readlines():读取文件所有行的内容成为列表,每一行都是列表中的一个元素,包含换行符\n
    r:只读
    r+:可读可写,不会创建不存在的文件,从顶部开始写,会覆盖之前此位置的内容
    eg:file = open('tes.txt','r+',encoding= 'utf-8')
        file.write('aaa')
        file.close()
    w+:可读可写,如果文件存在,则覆盖整个文件,不存在则创建
    eg:file = open('tes.txt','w+',encoding= 'utf-8')
        file.write('aaa')
        content = file.read()
        print(content)
        file.close()
    w:只能写,覆盖整个文件,不存在则会创建
    eg:file = open('tes.txt','w',encoding= 'utf-8')
        file.white('aaa')
        file.close()
    a:只能写,从文件底部添加内容,不存在则创建
    eg:file = open('tes.txt','a',encoding= 'utf-8')
        file.write('aaa')
        file.close()
    a+:可读可写 从文件顶部读取内容 从文件底部添加内容 不存在则创建
    eg:file = open('tes.txt','a+',encoding= 'utf-8')
        file.write('aaa')
        file.close()   写入内容
    eg:file = open('tes.txt','a+',encoding= 'utf-8')
        print(file.tell)
        file.seek(0)
        print(file.tell)
写:
write只能写入一个字符串
writelines:可以写入多行,传入一个列表
移动光标指针:seek
  file.seek(0)
获取文件指针位置:tell
  file.tell()
   
with open:默认文件读写结束后自动关闭,同时可以读写多个文件

csv文件读写:文件后缀名为.csv
import csv
a = csv.reader(open('D:/文件名'))
for row in a:
  print(row)
  写入时会默认形成一个空行

异常处理:

代码出现错误,解释器会中断当前模块代码的执行;
异常捕获:try
  try:
      异常内容
  except 捕获异常
 
(1)捕获指定异常类型:
eg:try:
      sfzs
      5 / 0
  except NameError
      print("NameError")
       
(2)捕获指定多种异常类型:
eg:try:
    print("hello")
    xzfcdz
    5 / 0
  except NameError
    print("NameError")
  except ZeroDivisionError
    print("ZeroDivisionError")
     
(3)捕获异常的详细信息:
eg:try:
    print("hello")
    xzfcdz
    汉字
  except NameError as e
    print("NameError",e)
  except ZeroDivisionError as e
    print("ZeroDivisionError",e)
   
(4)捕获任意类型异常:Exception
eg:try:
      5 / 0
      sdgsv
  except Exception:
      print("捕获所有异常")
     
eg:try:
      5 / 0
      sdgsv
  except Exception as e:
      print("捕获所有异常",e)
     
eg:try:
      5 / 0
      sdgsv
  except:
      print("捕获所有异常",traceback.format_exc())
捕获所有异常类型,等价于except Exception,并输出异常详细信息
异常抛出:raise
else:出现异常不会执行
finally:代码不论有无异常都会执行

 

猜你喜欢

转载自www.cnblogs.com/blog-apply/p/13200416.html