I am learning Python and I have been tasked with:
I have many files, all with different names, each 7 characters long. I was able to change the extensions but it feels very clunky. I am positive there is a cleaner way to write the following (but its functioning, so no complaints on that note):
import os, sys
path = 'C:/Users/dana/Desktop/text_files_2/'
for filename in os.listdir(path):
if filename.endswith('.rtf'):
newname = filename.replace('.rtf', '.txt')
os.rename(filename, newname)
elif filename.endswith('.py'):
newname = filename.replace('.py', '.txt')
os.rename(filename, newname)
elif filename.endswith('.TEXT'):
newname = filename.replace('.TEXT', '.txt')
os.rename(filename, newname)
elif filename.endswith('.text'):
newname = filename.replace('.text', '.txt')
os.rename(filename, newname)
I do still have a bit of a problem:
I can not figure out how to add "file_" to the start of each of the filenames [you would think that would be the easy part]. I have tried declaring newname as
newname = 'file_' + str(filename)
it then states filename is undefined.
Any assistance on my two existing issues would be greatly appreciated.
The basic idea would be first get the file extension part and the real file name part, then put the filename into a new string.
os.path.splitext(p)
method will help to get the file extensions, for example: os.path.splitext('hello.world.aaa.txt')
will return ['hello.world.aaa', '.txt']
, it will ignore the leading dots.
So in this case, it can be done like this:
import os
import sys
path = 'C:/Users/dana/Desktop/text_files_2/'
for filename in os.listdir(path):
filename_splitext = os.path.splitext(filename)
if filename_splitext[1] in ['.rtf', '.py', '.TEXT', '.text']:
os.rename(os.path.join(path, filename),
os.path.join(path, 'file_' + filename_splitext[0] + '.txt'))
Supply the full path name with os.path.join()
:
os.rename(os.path.join(path, filename), os.path.join(name, newname))
and you can run your program from any directory.
You can further simply your program:
extensions = ['.rtf', '.py', '.TEXT', '.text']
for extension in extensions:
if filename.endswith(extension):
newname = filename.replace(extension, '.txt')
os.rename(os.path.join(path, filename), os.path.join(path, newname))
break
All the other elif
statements are not needed anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With