《笨方法学习python3》练习15: Reading Files:open, close, read, repr

这篇博客介绍了Python中open()函数的使用,包括文件打开模式、编码处理以及错误处理。它展示了如何读取文件内容,强调了在读取文件后必须调用close()函数关闭文件的重要性。此外,还讨论了当文件以不同编码保存时可能出现的解码错误,并给出了使用repr()函数检查文件对象的示例。
摘要由CSDN通过智能技术生成

EX15: Reading Files

  • 例子:

    from sys import argv
    
    # 命令行输入
    script, filename = argv
    
    # 打开文件,并且返回文件操作对象
    txt = open(filename) # 有的时候open需要添加参数:encoding = "utf-8"
    
    # 使用 f-string 调用 filename
    print(f"Here's your file {filename}:")
    # 读取整个文件,将文件内容放到一个字符串变量中。
    print(txt.read())
    
    print("Type the filename again:")
    file_again = input(">")
    
    txt_again = open(file_again)
    # print(txt.read() == txt_again.read()) # false
    
    print(txt_again.read())
    
  • 学习内容:open()close()read()

    • open()
      • 打开文件,并且返回文件操作对象

      • 语法格式:

        open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

        • file:必需,文件路径(相对或者绝对路径)。

        • mode: 可选,文件打开模式

        • buffering:设置缓冲

        • encoding:一般使用utf8

        • errors:报错级别

        • newline:区分换行符

        • closefd:传入的file参数类型

        • opener:例如:t — 文本模式 (默认)。

          ​ r — 以只读方式打开文件。

          ​ rb — 以二进制格式打开一个文件用于只读。

          ​ w — 打开一个文件只用于写入。

          ​ wb — 以二进制格式打开一个文件只用于写入。

    • close()
      • 关闭文件,无参数,没有返回值

      • 语法格式:

        fileObject.close();

    • read()
      • 将文件内容读取到内存,返回从字符串中读取的字节。

      • 语法格式:

        fileObject.read();

        • size:从文件中读取的字节数。如有需要,在括号中输入需要读取的字节数。
  • Study Drills

    • 添加close()

      输入:

      from sys import argv
      script, filename = argv
      
      txt = open(filename) 
      
      print(f"Here's your file {filename}:")
      print(txt.read())
      txt.close()
      
      print("Type the filename again:")
      file_again = input(">")
      
      txt_again = open(file_again)
      
      print(txt_again.read())
      txt_again.close()
      

      结果:

      python ex15.py nfile.txt
      Here's your file nfile.txt:
      This is a test file.
      
      Type the filename again:
      >nfile.txt
      This is a test file.
      
  • 改变代码(寻找可能情况及错误)

    • 关闭文档后再读取文档(执行close()后再执行read())

      输入:

      from sys import argv
      script, filename = argv
      
      txt = open(filename)
      txt.close()
      
      print(f"Here's your file {filename}:")
      print(txt.read())
      

      结果:

      python ex15.py ceshi.txt
      Here's your file ceshi.txt:
      Traceback (most recent call last):
        File "ex15.py", line 14, in <module>
          print(txt.read())
      ValueError: I/O operation on closed file.
      

      值错误:已经关闭的文档不能执行操作

    • 保存txt文档不是utf-8编码会导致无法读取

      输入:

      from sys import argv
      script, filename = argv
      
      txt = open(filename)
      print(f"Here's your file {filename}:")
      print(txt.read())
      

      结果:

      echo "test">1.txt
      python TEST.py 1.txt
      Here's your file 1.txt:
      Traceback (most recent call last):
        File "TEST.py", line 14, in <module>
          print(txt.read())
      UnicodeDecodeError: 'gbk' codec can't decode byte 0xff in position 0: illegal multibyte sequence
      

      错误的意思是:Unicode的解码(Decode)出现错误(Error)了,以gbk编码的方式去解码(该字符串变成Unicode),但是此处通过gbk的方式,确无法解码(can‘t decode)。“illegal multibyte sequence”意思是非法的多字节序列,即没法(解码)了。

      此种错误,可能是要处理的字符串本身不是gbk编码,但是却以gbk编码去解码 。比如,字符串本身是utf-8的,但是却用gbk去解码utf-8的字符串,所以结果不用说,则必然出错。

      echo 命令会将创建一个叫”1.txt“的文档,将”test“写入文档中。

      修改:

      from sys import argv
      script, filename = argv
      
      txt = open(filename,encoding = 'utf-16')
      print(f"Here's your file {filename}:")
      print(txt.read())
      

      结果:

      python TEST.py 1.txt
      Here's your file 1.txt:
      test
      

      因为在powershell中,echo命令创建的文档,默认编码是”utf-16",所以设置encoding = 'uft-16'

      参考链接:123

    • repr()来查看不懂的地方

      输入:

      from sys import argv
      script, filename = argv
      
      txt = open(filename)
      print(">>>txt:",repr(txt)) 
      txt.close()
      
      txt = open(filename, encoding = 'utf-16')
      print(">>>txt:",repr(txt)) 
      

      结果:

      python TEST.py 1.txt
      >>>txt: <_io.TextIOWrapper name='1.txt' mode='r' encoding='cp936'>
      >>>txt: <_io.TextIOWrapper name='1.txt' mode='r' encoding='utf-16'>
      

      通过repr()可以知道txt的信息。open(filename)会返回文件对象,并将文件对象赋给txt,所以txt是一个文件对象,而不是文件本身。

      挖个坑(还不知道_io.TextIOWrapper的意思)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值