I am learning Python and I was instructed:
- adding "file_" to the beginning of each name in the directory
- extension change (currently the directory contains 4 different types: .py, .TEXT, .rtf, .text)
I have many files, all with different names, each of 7 characters. I was able to change the extensions, but it feels very awkward. I am sure there is a cleaner way to write the following (but its functioning, so no complaints about this 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 still have a problem:
- The script must currently be inside my directory to run it.
I canโt figure out how to add โfile_โ to the beginning of each of the file names [you think this will be the easy part]. I tried to declare newname as
newname = 'file_' + str(filename)
it indicates that the file name is undefined.
.