Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

python - Unrar the files with the name of the rar files

I have folder with 4 rar (zipped) files.

screenshot #1: rar files and names

This is the python code to unrar them:

#!/usr/bin/python
import os, zipfile, pyunpack, sys
import tkinter as tk
from tkinter import filedialog
from tkinter.filedialog import askdirectory

root = tk.Tk()
root.withdraw()

basis_folder = askdirectory(title='Select Folder')
    
for root, dirs, files in os.walk(basis_folder):
    for filename in files:
        if filename.endswith(".rar") :
            print('RAR:'+os.path.join(root,filename))
        elif filename.endswith(".zip"):
            print('ZIP:'+os.path.join(root,filename))
        name = os.path.splitext(os.path.basename(filename))[0]
        if filename.endswith(".rar") or filename.endswith(".zip"):
            try:
                arch = pyunpack.Archive(os.path.join(root,filename))
                # os.mkdir(name)
                arch.extractall(directory=root)
                os.remove(os.path.join(root,filename))
            except Exception as e:
                print("ERROR: BAD ARCHIVE "+os.path.join(root,filename))
                print(e)
                try:
                    # os.path.join(root,filename)os.remove(filename)
                    pass
                except OSError as e: # this would be "except OSError, e:" before Python 2.6
                    if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory
                        raise # re-raise exception if a different error occured
                    sys.exit()
os._exit(0)

After unrar process, the code deletes the rar files and extract the files inside rar files. I want the rename of the files as file1 from rarfile1, file2 from rarfile1, file3 from rarfile1, file1 from rarfile2, so on...

This is the result I want:

[screenshot #2: unrar files and their new names]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
/root/
    - example1.rar
    - example2.rar

One way to achieve this would be to do these steps,there would definitely be a better way I believe though:

  1. Temporarily create a directory with the same name as your rar file. (A directoty /root/example1/ for /root/example1.rar file
  2. Move the Rar file to the temporary directory /root/example1/example1.rar
  3. Extract all files from example1.rar file to example1 directory
    /root/
         example1/
         file1.ext
         file2.ext
         example1.rar
  1. Delete the rar file
 /root/    
      example1/
      file1.ext
      file2.ext
  1. Rename all files in example1 directory to example1_file1.ext
    /root/
       /example1/
               example1_file1.ext
               example1_file2.ext
  1. Move all files to /root/
        /root/
               /example1/
               example1_file1.ext
               example1_file2.ext
  1. Delete /example1/ directory :
        /root/
               example1_file1.ext
               example1_file2.ext
  1. Loop through all Rars this way. End result :

     /root/
            example1_file1.ext
            example1_file2.ext
            example2_file1.ext
            example2_file2.ext
    

I have not run and validated the code - but your code will get modified along below lines :

for root, dirs, files in os.walk(basis_folder):
for filename in files:
    if filename.endswith(".rar"):
        print('RAR:' + os.path.join(root, filename))
    elif filename.endswith(".zip"):
        print('ZIP:' + os.path.join(root, filename))
    name = os.path.splitext(os.path.basename(filename))[0]
    if filename.endswith(".rar") or filename.endswith(".zip"):
        try:
            # root/yourfile.rar
            curr_file_path = os.path.join(root, filename)
            # root/yourfile/
            new_file_dir = curr_file_path.split('.')[0]
            # root/yourfile/yourfile.rar
            new_file_path = os.path.join(new_file_dir, filename)
            os.mkdir(new_file_dir)
            os.replace(curr_file_path, new_file_path)
            arch = pyunpack.Archive(new_file_path)
            # extract files to root/yourfile
            arch.extractall(directory=new_file_dir)
            # Remove the Rar file
            os.remove(new_file_path)
            files_in_curr = [f for f in os.listdir(new_file_dir) if os.path.isfile(f)]
            for file in files_in_curr:
                new_name = os.path.join(new_file_dir, filename.split('.')[0] + '_' + file)
                # Rename file from root/yourfile/file1.ext to root/yourfile/yourfile_file1.ext
                os.rename(os.path.join(new_file_dir, file), new_name)
                # move file from root/yourfile/yourfile_file1.ext to root/yourfile_file1.ext
                os.replace(os.path.join(new_file_dir, new_name), os.path.join(root, new_name))
            # Remove the temporary empty directory
            os.rmdir(new_file_dir)

        except Exception as e:
            print("ERROR: BAD ARCHIVE " + os.path.join(root, filename))
            print(e)
            try:
                # os.path.join(root,filename)os.remove(filename)
                pass
            except OSError as e:  # this would be "except OSError, e:" before Python 2.6
                if e.errno != errno.ENOENT:  # errno.ENOENT = no such file or directory
                    raise  # re-raise exception if a different error occured
                sys.exit()
  os._exit(0)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...