-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrename_files.py
executable file
·74 lines (58 loc) · 2.24 KB
/
rename_files.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env python3
import os
import magic
import subprocess
import importlib
def install_package(package):
"""Installs a package using pip."""
try:
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
except subprocess.CalledProcessError:
print(f"Error installing {package}")
def import_module(module_name):
"""Imports a module."""
try:
importlib.import_module(module_name)
except ImportError:
print(f"{module_name} is not installed. Installing...")
install_package(module_name)
importlib.import_module(module_name)
def main():
install_and_import('magic')
import magic
path = input("Directory file path?: ")
# Error handling
try:
if not os.path.isdir(path):
raise ValueError("The provided path is not a directory.")
video_count = 0 # Track the number of video files
# Iterate over directory
for filename in os.listdir(path):
filepath = os.path.join(path, filename)
# Use magic to determine file type
mime_type = magic.from_file(filepath, mime=True)
if mime_type and mime_type.startswith('video/'):
video_count += 1
if video_count > 1:
print("Multiple video files found in the directory. Skipping renaming.")
break
directory_name = os.path.basename(path)
new_filename = directory_name + os.path.splitext(filename)[1]
new_filepath = os.path.join(path, new_filename)
try:
os.rename(filepath, new_filepath)
print(f"Video file '{filename}' renamed to '{new_filename}'")
except OSError as e:
print(f"Error renaming file: {e}")
else:
print(filename) # Not a video file
except FileNotFoundError:
print("Directory: {0} does not exist".format(path))
except NotADirectoryError:
print("{0} is not a directory".format(path))
except PermissionError:
print("You do not have permissions to change to {0}".format(path))
except ValueError as e:
print(e)
if __name__ == "__main__":
main()