Home > Software design >  python error:IsADirectoryError: [Errno 21] Is a directory
python error:IsADirectoryError: [Errno 21] Is a directory

Time:12-07

I am trying to decompress a list of .xz file and save them in a single folder,my code is show below

import shutil
path = "/content/drive/MyDrive/dataset_demo/Posts/"
output_path = "/content/sample_data/output/"
os.chdir(path)

for file_com in os.listdir(path):
  if file_com.endswith('.xz'):
    with lzma.open(file_com,'rb') as input:
      with open(output_path,'wb') as output:
        shutil.copyfileobj(input, output)

it noticed me that:"IsADirectoryError: [Errno 21] Is a directory: '/content/sample_data/output/'" and I know the final aim should be a file but how could I save them in a folder

What should I do next, and thanks for your help and time.

CodePudding user response:

It looks like you're trying to open the output_path as a file, but it's actually a directory. You'll need to specify the name of the file you want to write to within the output_path directory.

import shutil
import os
import lzma

path = "/content/drive/MyDrive/dataset_demo/Posts/"
output_path = "/content/sample_data/output/"
os.chdir(path)

for file_com in os.listdir(path):
  if file_com.endswith('.xz'):
    with lzma.open(file_com,'rb') as input:
      # Create the output file path
      output_file_path = os.path.join(output_path, file_com[:-3])
      with open(output_file_path,'wb') as output:
        shutil.copyfileobj(input, output)

In this code, I've added the os.path.join() function to create the output file path. This function combines the output_path directory with the file name (excluding the .xz extension) to create the full path to the output file.

  • Related