DEV Community

Cover image for Rename and Delete files with Python
Lucas de Brito Silva
Lucas de Brito Silva

Posted on

1

Rename and Delete files with Python

Every day I find myself in need of doing tiring jobs that can be replaced by scripts and that the computer can help me too much, so one day I thought "Okay, I got tired, from now on I refuse to do that kind of work!" and from then on things only got better.

Since college, I created a great bond with the Python programming language, and we became great friends. That way I developed a script with him that would save my life!

Alt Text

In my work sometimes I needed to rename files from a list or even delete them from a folder, because they were no longer useful. So my first approach was to create two functions.

The first function was to rename files, so that they had a pattern and an order, like: file_1, file_2 and so on.

# Pythono3 code to rename multiple
import os
import glob
def main():
caminho = "path/to/archives/"
for i, arquivo in enumerate(glob.glob(os.path.join(caminho, "*.jpg"))):
new_file = caminho + "name" + str(i) + ".jpg"
os.rename(arquivo, new_file)
if __name__ == '__main__':
main()
view raw rename.py hosted with ❤ by GitHub

The heart of this code, as you can see, is in the os.rename that renames from the old name to the new file name.
NOTE: One very cool thing is that the script renames the whole way, so it makes use of the glob.

The second problem was that I needed to delete all files that were not on a .txt list (believe me, that list was over 100 files). So I used a very similar approach, but with the use of pandas, to read the txt file, of .index to try to find the file and os.remove to remove the files outside the list. The code is shown below.

import os
import glob
import pandas as pd
def main():
data = pd.read_csv('/path/of/txt/', sep=" ", header=None)[0].values.tolist()
caminho = "/path/of/files"
finded = 0
deleted = 0
for arquivo in glob.glob(os.path.join(caminho, "*.jpg")):
arquivo = arquivo.replace(caminho,'')
try:
data.index(arquivo)
finded += 1
except:
os.remove(caminho + arquivo)
deleted += 1
print("Encontrados: ", finded)
print("Deletados: ", deleted)
if __name__ == '__main__':
main()
view raw remove.py hosted with ❤ by GitHub

And it's because of scripts like these that I have time today to write this article for you. I hope you like it and that it helped!

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More