The readTextFile() method of Python learning records

Planning to write a method to read a text file, readTextFile()

The following is my code:

#encoding=utf-8
import os
def readTextFile():
  fname=input("请输入文件名:")
  try:
    fobj=open(fname,'r')
  except (IOError,e):
    print('文件打开错误:',e)
  else:
    for eachLine in fobj:
      print(eachLine,)
      fobj.close()
readTextFile()
Then it reported the error of UnicodeDecodeError:'gbk' codec can't decode byte 0x88 in position 20: illegal multibyte sequence

So after querying the data, I added encoding='UTF-8' to the open built-in function. In the open() function, fname is the file name, r is reading, and encoding=utf-8. What I understand is that fname is utf -8 character form to open read-only

Then the code becomes as follows:

#encoding=utf-8
import os
def readTextFile():
  fname=input("请输入文件名:")
  try:
    fobj=open(fname,'r',encoding='UTF-8')
  except (IOError,e):
    print('文件打开错误:',e)
  else:
    for eachLine in fobj:
      print(eachLine,)
      fobj.close()
readTextFile()
But still another error was reported:

ValueError: I/O operation on closed file.

After inspection, it was found that my fobj.close() had a problem with the indentation. It was placed under the for loop and an error was reported, so I moved fobj.close() out of the for loop.

The final code is:

#encoding=utf-8
import os
def readTextFile():
  fname=input("请输入文件名:")
  try:
    fobj=open(fname,'r',encoding='UTF-8')
  except (IOError,e):
    print('文件打开错误:',e)
  else:
    for eachLine in fobj:
      print(eachLine,)
    fobj.close()
readTextFile()












Guess you like

Origin blog.csdn.net/dream_18/article/details/78974201