Looping through each subfolder and moving all http.log files to another folder. Each subfolder contains http.log file. To overcome name overlapping used the index but it giving me an error. Please help
target_folder = './destination'
source_folder = './origin'
index =1
for path,dir,files in os.walk(source_folder):
if 'http.log' in files : os.rename(os.path.join(path,'http.log'),os.path.join(target_folder,'data
({}).log'.format(index)))
index =1`
CodePudding user response:
If your goal is only to find a single http.log
file somewhere in the source folder and move it to the target folder, you can use pathlib.Path.glob()
to do the work of finding, then just move the first one it finds:
import pathlib
target_folder = pathlib.Path('new_folder_with_http')
source_folder = pathlib.Path('original_data')
found_files = list(source_folder.glob('**/http.log'))
found_files[0].rename(target_folder / 'http.log')
CodePudding user response:
files
is a list; you want to check if this file name is a member.
target_folder = new_folder_with_http
for path, dir, files in os.walk(original_data):
if "http.log" in files:
os.rename(
os.path.join(path, "http.log"),
os.path.join(target_folder, "http.log"))
There is no os.move
; I guess you want os.rename
or perhaps shutil.move
.
Notice also how we need to prefix the path
(the directory it was found in) back in front of the bare file name.
The else
clause is optional; just don't put one if you don't have any code to put there.
The same file name can only exist once in targetdir
so this will fail on Windows if it finds multiple files with the same name. On Unix, or if you switch to shutil.move
, it will replace all the found files in targetdir
with the last one found. If you don't want either of those things to happen, you'll have to specify a way to make each file name unique after moving, perhaps by renaming it to reflect which directory it was found in somehow.
Here is a simple loop to add a numeric suffix if the file already exists:
...
if "http.log" in files:
dest = os.path.join(target_folder, "http.log"))
suf = None
while os.path.exists(dest):
if suf is None:
suf = 1
else:
suf = 1
dest = os.path.join(target_folder, "http.log." str(suf))
os.rename(
os.path.join(path, "http.log"),
dest)