How to deal with python file reading failure

When reading files, such as reading xxx.csv , encoding errors may be reported

Similar to

'xxx' codec can't decode byte 0xac in position 211: illegal multibyte sequen

id_list = []
with open('E:/work_spider/xxx/xx.csv', "r", encoding="utf-8") as csvfile:
  csvReader = csv.reader(csvfile)
  for content in csvReader:
    content = str(content)
    if 'l.' in content:
      continue
    id_list.append(content.split('\\')[0].replace("['", ""))


You can try to develop an encoding method when reading.

Unicode decode error xxxxxxxxxxx may also be reported when saving pictures or video files

VideoHtmlContent = requests.get(url = VideoUrl,headers=headers).content
with open('bobovideo.mp4','wb',) as f:
  f.write(VideoHtmlContent)


Don't forget its file opening method, pictures and videos are all requested and written in bytes type binary mode. We use'wb' to open in binary writing mode

There are many open modes for open. The following are for reference and reference only:

a means append, r means read, w means write, and + means read and write mode. , B means binary, t means text mode, and t is the default mode.

w is opened in writing mode, a is opened in append mode (starting from EOF, create a new file if necessary) r+ opened in read-write mode w+ opened in read-write mode a+ opened in read-write mode rb opened in binary read mode wb in binary writing Open ab in binary mode, open rb+ in binary append mode, open wb+ in binary read-write mode, open ab+ in binary read-write mode, open

Question extension:

Python file reading: errors encountered and solutions

TypeError: 'str' object is not callable

cause:

The error TypeError:'str' object is not callable literally means: that str cannot be called by the system,

In fact, the reason is: you are calling a variable or object that cannot be called. The specific manifestation is that you call the function or variable in the wrong way.

example:

filePath=kwargs['path']
filePathStr=str(filePath)


That is, I am using keyword parameters to pass parameters, what type is passed when it is passed, what type is passed, that is, filePath is originally a string type, but I used the str() function to act on it. This is the problem, the function call is wrong!

So far, this article on how to deal with python file reading failures is introduced. For more related python file reading failures, please search for previous articles or continue to browse related articles below. Hope you will support you in the future!


Guess you like

Origin blog.51cto.com/14825302/2543253