CodingStark
CodingStark

Reputation: 199

Remove certain strings from filenames inside a folder

I have a folder that contains a bunch of text files.

32167.pdf.txt
20988.pdf.txt
45678.pdf.txt
:
:
99999.pdf.txt

I would like to remove ".pdf" from all the filenames inside that folder (As showed below).

32167.txt
20988.txt
45678.txt
:
:
99999.txt

I tried to use os to do it but throwing me an error FileNotFoundError: [Errno 2] No such file or directory: '.txt' -> '.txt'

Here is my code:

for filename in os.listdir('/Users/CodingStark/folder/'):
    os.rename(filename, filename.replace('.pdf', ''))

I am wondering are there any other ways to achieve this instead of using os? Or os is the fastest way to do it? Thank you!!

Upvotes: 0

Views: 1012

Answers (2)

Tomerikoo
Tomerikoo

Reputation: 19431

You should really use pathlib when working with paths. It has alternatives for most of the os functions and it just makes more sense to use and is definitely more portable.

To the task in hand:

from pathlib import Path

root = Path('/Users/CodingStark/folder/')
for path in root.glob("*.pdf.txt"):
    path.rename(path.with_name(path.name.replace(".pdf", "")))
#               or:
#               path.with_suffix('').with_suffix(".txt")
#               or:
#               str(path).replace(".pdf", "")

Upvotes: 1

CryptoFool
CryptoFool

Reputation: 23129

I think I know what's wrong. filename will contain just the file's name, not a complete path. Try this:

dir = '/Users/CodingStark/folder/'
for filename in os.listdir(dir):
    os.rename(dir + filename, dir + filename.replace('.pdf', ''))

Upvotes: 3

Related Questions