Home > Back-end >  Python: How to loop through a directory of files and move text at the end of a filename to the begin
Python: How to loop through a directory of files and move text at the end of a filename to the begin

Time:08-26

I have a list of files in my C drive that I'd like to loop through and move all the text within the parenthesis, to the beginning of the file name. Then delete the open/close parenthesis

For example I have a file called ABC 123 File (Address, Zip Code).PDF

The output would then be Address, Zip Code ABC 123 File.PDF

CodePudding user response:

Use re.sub() to match the parts of the filename inside and outside the (), and swap the order in the result.

import re
import glob
import os

folder = 'C:/path/to/folder'
for file in glob.glob(os.path.join(folder, '*.PDF')):
    name = os.path.basename(file)
    newname = re.sub(r'^(.*) \((.*)\).PDF$', r'\2 \1.PDF', name)
    os.rename(os.path.join(folder, name), os.path.join(folder, newname))

CodePudding user response:

Split the filename into parts, and reconfigure them. Here is a super simple example:

#assuming all files are formatted like this

file = "ABC 123 File (Address, Zip Code).PDF"

#split filename
file = file.split("(")

#Make sure to ignore the .PDF
temp = file[1].split(".")

# Get the address and zip code
data = temp[0].split(",")
address = data[0]
zip_code = data[1]

#get rid of extra parenthesis
zip_code = zip_code.replace(")", "")

# Append to beginning of filename, and add file ending
file = f"{address}{zip_code} "   file[0]   "."    temp[1]

print(file)


CodePudding user response:

This is fairly straightforward.

  1. Loop through directory for each file
  2. Change each filename

There are many ways to do both of these steps. I'd suggest, searching stackoverflow.

Here's an example:

import glob
import os

dir_path = r'C:\test'

for fullname in os.listdir(dir_path):
    filename, _, ext = fullname.rpartition('.')
    first_part, address = filename.split('(')
    first_part, address = first_part.strip(), address[:-1]

    os.rename(f'{dir_path}/{fullname}', f'{dir_path}/{address} {first_part}.{ext}')
    

CodePudding user response:

This few lines of code will do the job:

import os
import shutil

# files path
os.chdir('C:\\Users\\DELL\\Documents\\Python Scripts')
for filename in os.listdir():
    newfilename=""
    if filename.endswith(').pdf'):
    print(filename)
    index = filename.find("(")
    newfilename=filename[index 1:-5] " " filename[:index] ".pdf"
    print(newfilename)
    shutil.move(filename,newfilename)

steps: 1- loop through the pdf files in the folder you want.

2- split the file name than reorder it.

  • Related