-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_rename_util.py
More file actions
58 lines (44 loc) · 1.74 KB
/
Copy pathfile_rename_util.py
File metadata and controls
58 lines (44 loc) · 1.74 KB
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
### Written by Laura Jones ####
### 10/10/2025 ####
### Find me on GitHub : github.com/LJones-alt
### I offer no guarentee of safety or accuracy of this software ###
## import all packages
import os
## create a class - this means we can reuse it later
class RenameUtil:
## init the class and run some functions automatically
def __init__(self, folder_path: str = "", new_names : str = ""):
self.dir = folder_path
self.nameFile = new_names
self.newNames = self._loadNewNames()
self.files: list[str] = self._listFiles()
## private / internal function that finds
## all the files in your folder
def _listFiles(self)-> list[str]:
files =os.listdir(self.dir)
return files
## private / internal function that finds
## the index of the filename
def _findIndex(self, filename : str):
data = filename.split("_")
index = int(data[2])
return index
## internal function that loads all the new filenames
def _loadNewNames(self):
names = []
with open(self.nameFile) as f:
for line in f:
names.append(line[:-2])
return names
## public function that renames all files in the directory
def rename(self):
for file in self.files:
index = self._findIndex(file)
os.rename(f"{self.dir}/{file}", f"{self.dir}/{self.newNames[index]}.raw")
### To use :
## 'rename_files = RenameUtils("<folder location>", "<text file with new names>")
## rename.rename()
## example:
rename = RenameUtil("/home/laura/Documents/repos/misc_python/test_files", "new_names.txt")
rename.rename()
## then in the terminal you run "python3 file_rename_util.py"