Salim Farhat
Salim Farhat

Reputation: 21

remove characters from every file name in directory with python

So I am writing a piece of code that needs to iterate through hundreds of files in a directory. With every filt it needs to filter out certain pieces of information in it then put it in a new file with a modified name.

For example, a file called 1100006_0.vcf or 5100164_12.vcf must have a file created called 1100006.vcf and 5100164.vcf respectively. Can you point me in the right direction for this?

Upvotes: 1

Views: 2175

Answers (2)

Salim Farhat
Salim Farhat

Reputation: 21

As posted by RavinderSingh13, the code was fine, the only issue was that in renaming them, I would have two files of the same name (the difference between them was the underscore and number that I needed removed).

#!/usr/bin/python3
import os

DIRNAME="/tmp"
files = os.listdir(DIRNAME)
for f in files:
    if '.vcf' in f:
        newname = f.split('_')[0]
        newname = newname + '.vcf'
        os.rename(f, newname)

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133508

EDIT: To make code Generic and rename file names from one directory to any other directory/folder try following. I have kept this program inside /tmp and renamed the files inside /tmp/test and it worked fine(in a Linux system).

#!/usr/bin/python3
import os
DIRNAME="/tmp/test"
files = os.listdir(DIRNAME)
for f in files:
    if '.vcf' in f:
        newname = f.split('_')[0]
        newname = newname + '.vcf'
        os.rename(os.path.join(DIRNAME,f), os.path.join(DIRNAME,newname))


Since you want to rename the files, so we could use os here. Written and tested with shown samples in python3, I have given DIRNAME as /tmp you could give your directory where you want to look for files.

#!/usr/bin/python3
import os

DIRNAME="/tmp"
files = os.listdir(DIRNAME)
for f in files:
    if '.vcf' in f:
        newname = f.split('_')[0]
        newname = newname + '.vcf'
        os.rename(f, newname)

Upvotes: 3

Related Questions