Python save the file name, line 257, in urlretrieve tfp = open(filename, ‘wb’) OSError: [Errno 22] Invalid argument:

created at 11-21-2021 views: 23

1. Problem description

import urllib.request
filename ='File name*File name/File name.zip'
urllib.request.urlretrieve( "https://www.......com//1234.zip",filename)

The python crawler downloads the file, saves the file name, and reports an error

urllib.request.urlretrieve( "https://www.......com","file name*file name/file name.zip")
   File "C:\Users\lenovo7\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 257, in urlretrieve
     tfp = open(filename,'wb')
OSError: [Errno 22] Invalid argument:'File name*File name/File name.zip'

cause of the problem

In the crawler scene, we have obtained the links and names of many files. The names contain special characters /, \, :, *, ?, ", <, >, |, which are not supported by windows naming.

solution

Before downloading and saving the file, the file name needs to be processed, and the unsupported characters are replaced with blanks

import urllib.request
filename ='File name*File name/File name.zip'
sets = ['/','\\',':','*','?','"','<','>','|']
for char in filename:
     if char in sets:
         filename = filename.replace(char,'')
urllib.request.urlretrieve( "https://www.......com//1234.zip",filename)
created at:11-21-2021
edited at: 11-21-2021: