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

时间:2018-07-24 16:11:54

标签: python python-3.x parsing

我正在尝试编写一个嵌套的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)

1 个答案:

答案 0 :(得分:0)

问题行为files = os.listdir(source),您无法执行listdir 对单个文件进行操作。相反,您应该直接跳至move操作:

...
except:
    #If it's just a .txt or .log file 
    source = tmp_file.name
    dest = dirpath

    shutil.move(source, dest)