Ive got a bunch of files in a folder all with the same extension:
[movie] Happy feet 2021-04-01 22-00-00.avi [movie] Dogs Life 2021-06-01 22-03-50.avi etc would like to rename the start and end to: Happy feet.avi Dogs Life.avi etc
Here is what I have so far:
import shutil
import os
source_dir = r"C:\\Users\\ED\\Desktop\\testsource"
target_dir = r"C:\\Users\\ED\\Desktop\\testdest"
data = os.listdir(source_dir)
print(data)
new_data = [file[8:].split(' 2021')[0] + '.txt' for file in data]
print(new_data)
for file in data:
os.replace(data, [file[8:].split(' 2021')[0] + '.txt')
for file_name in data:
shutil.move(os.path.join(source_dir, file_name), target_dir)
Im having trouble with the os.rename() part after I printed it out.
You can use (tested):
from glob import glob
import re
import shutil
import os
src = "C:/Users/ED/Desktop/testsource"
dst = "C:/Users/ED/Desktop/testdest"
for f in glob(f"{src}/**"):
fn = os.path.basename(f)
new_fn = re.sub(r"^\[.*?\](.*?) \d{4}-\d{2}-\d{2} \d{2}-\d{2}-\d{2}(\..*?)$", r"\1\2", fn).strip()
shutil.move(f, f"{dst}/{new_fn}")
For python 2:
for f in glob(src+"/**"):
fn = os.path.basename(f)
new_fn = re.sub(r"^\[.*?\](.*?) \d{4}-\d{2}-\d{2} \d{2}-\d{2}-\d{2}(\..*?)$", r"\1\2", fn).strip()
shutil.move(f, dst+"/"+new_fn)