目录名称对于我的临时文件夹错误无效吗?

2024-04-26 08:10:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个嵌套的try except语句,该语句打开.zip、.gz和.tar文件夹,并且也是常规的。txt文件。我正在从internet下载这些文件,并将它们解压缩到一个临时文件夹中。我的代码适用于.zip、.gz和.tar文件夹,但它表示我的目录名对于我试图提取到临时文件夹的常规.txt文件无效。这是我的密码。你知道吗

def function(file_download_url):

   urllib.request.urlopen(file_download_url) #download the zipped file
   dirpath = tempfile.mkdtemp() #Generate a temporary directory 


   #Download the URL as an temporary file that has to be deleted later on
   with urllib.request.urlopen(file_download_url) as response:
      with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
        shutil.copyfileobj(response, tmp_file)

   print(tmp_file.name) #To display the name of the temporary file created

   #Try-Except statement that extracts compressed files to a temporary directory generated
   try:
       #If it's a .zip file
       with ZipFile(tmp_file.name) as my_zip_file: #Open up the downloaded zipped file
           my_zip_file.extractall(dirpath) #extract the support bundle to the temporary directory created 
           path = dirpath #Make the temporary directory the path for searching
   except:
       try:
           #If it's a .gz or .tar file 
           with tarfile.open(tmp_file.name) as tar:
               tar.extractall(dirpath)
               path = dirpath
               print(path)
       except:
           #If it's just a .txt or .log file 
           source = tmp_file.name
           dest = dirpath

           files = os.listdir(source) #Here is where the error "The directory name is invalid" occurs 

           for f in files:
               shutil.move(source, dest)

Tags: thepathname文件夹downloadaswithtar