1
1
import os
2
-
3
2
from stringutils import randomstring
4
3
from configs import SAVEDICTNAME
5
4
from exceptions import (TargetExtensionError ,
6
5
ExhaustedNamesError )
6
+ from files_iter import get_file_iterator
7
+
8
+ def serialrename (basename : str , pathstring : str , ext : str , subtree :bool , savedict = False )-> dict :
9
+ '''Renames files of a given extension in a directory using title as the base filename followed by a serial number.
10
+ By default it returns a dict with keys being the original names and values being the new
11
+ names if successful.
12
+ ext = file extension to be affected
13
+ If savedict is set to True a names_table tabseparated file is saved with the names relation is saved in
14
+ patstring directory.'''
15
+ renamingdict = {}
16
+ for count , f in enumerate (get_file_iterator (pathstring , subtree , ext = ext )):
17
+ newname = f .parent .joinpath (f"{ basename } _{ count } { ext } " )
18
+ os .rename (str (f ), newname )
19
+ renamingdict .update ({f .name : newname .name })
20
+ if savedict and renamingdict :
21
+ write_names_relation_table (pathstring , renamingdict )
22
+ return renamingdict
23
+
7
24
8
25
def blindrename (pathstring : str , ext : str , savedict = False )-> dict :
9
- '''Blindly renames files of a given extension in a directory to a 4 random letters string. By default it
10
- returns a dict with keys being the original names and values being the new
11
- names if successful.
26
+ '''Blindly renames files of a given extension in a directory to a 4 random letters string. By default it
27
+ returns a dict with keys being the original names and values being the new
28
+ names if successful.
12
29
ext = file extension to be affected
13
30
If savedict is set to True a names_table tabseparated file is saved with the names relation is saved in
14
31
patstring directory.'''
@@ -37,15 +54,23 @@ def blindrename(pathstring: str, ext: str, savedict=False)-> dict:
37
54
renamingdict .update (
38
55
{f : "{newname}{ext}" .format (newname = randomname , ext = ext )})
39
56
break
57
+
40
58
if savedict and renamingdict :
41
- dictfile = os .path .join (pathstring , SAVEDICTNAME )
42
- with open (dictfile , "w" ) as names_table :
43
- names_table .write ("OLD NAME\t NEW NAME\n " )
44
- for old_name , new_name in renamingdict .items ():
45
- names_table .write ("{old}\t {new}\n " .format (
46
- old = old_name , new = new_name ))
59
+ write_names_relation_table (pathstring , renamingdict )
60
+
47
61
return renamingdict
48
62
63
+ def write_names_relation_table (pathstring :str , renamingdict :dict ):
64
+ '''
65
+ Writes a txt file with the name relation contained in the renaming dict.
66
+ '''
67
+ dictfile = os .path .join (pathstring , SAVEDICTNAME )
68
+ with open (dictfile , "w" ) as names_table :
69
+ names_table .write ("OLD NAME\t NEW NAME\n " )
70
+ for old_name , new_name in renamingdict .items ():
71
+ names_table .write ("{old}\t {new}\n " .format (
72
+ old = old_name , new = new_name ))
73
+
49
74
def undolastrename (pathstring : str )-> dict :
50
75
'''Restore original name of files in pathstring directory according to names table in
51
76
pathtosavedict path.
@@ -59,7 +84,7 @@ def undolastrename(pathstring: str)-> dict:
59
84
60
85
if not os .path .isdir (pathstring ):
61
86
raise FileNotFoundError ("{pathstring} is an invalid directory or does not exists" .format (pathstring = pathstring ))
62
-
87
+
63
88
pathtosavedict = os .path .join (pathstring , SAVEDICTNAME )
64
89
65
90
with open (pathtosavedict , "r" ) as namesdict :
@@ -68,12 +93,12 @@ def undolastrename(pathstring: str)-> dict:
68
93
"success" :[],
69
94
"notfound" : [],
70
95
"conflict" : []
71
- }
96
+ }
72
97
for l in namesdict :
73
98
names = l [:- 1 ].split ("\t " )
74
99
try :
75
- originalname = os .path .join (pathstring , names [0 ])
76
- actualname = os .path .join (pathstring , names [1 ])
100
+ originalname = os .path .join (pathstring , names [0 ]. trim () )
101
+ actualname = os .path .join (pathstring , names [1 ]. trim () )
77
102
os .rename (actualname , originalname )
78
103
except (FileExistsError , PermissionError ):
79
104
result ["conflict" ].append (originalname )
@@ -91,6 +116,10 @@ def undolastrename(pathstring: str)-> dict:
91
116
return result
92
117
93
118
if __name__ == "__main__" :
94
- files = r"D:\OneDrive - The University of Queensland\Code learning\code-sandbox\Python\misc_utils\blindrename\test"
95
- result = undolastrename (files ) #blindrename(files, ".txt",savedict=True)
119
+ from stringutils import randomstring
120
+ files = r"test"
121
+ basename = randomstring (4 )
122
+ ext = ".txt"
123
+ subtree = False
124
+ result = serialrename (basename , files , ".txt" , subtree , savedict = True )
96
125
print (result )
0 commit comments