/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:
- Temporarily create a directory with the same name as your rar file. (A directoty /root/example1/ for /root/example1.rar file
- Move the Rar file to the temporary directory
/root/example1/example1.rar
- Extract all files from example1.rar file to example1 directory
/root/
example1/
file1.ext
file2.ext
example1.rar
- Delete the rar file
/root/
example1/
file1.ext
file2.ext
- Rename all files in example1 directory to example1_file1.ext
/root/
/example1/
example1_file1.ext
example1_file2.ext
- Move all files to /root/
/root/
/example1/
example1_file1.ext
example1_file2.ext
- Delete /example1/ directory :
/root/
example1_file1.ext
example1_file2.ext
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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…