问题
I have a bunch of files that do not have an extension to them.
file needs to be file.txt
I have tried different methods (didn't try the complicated ones since I am just learning to do a bit of advanced python).
here is one that I tried:
import os
pth = 'B:\\etc'
os.chdir(pth)
for files in os.listdir('.'):
changeName = 'files{ext}'.format(ext='.txt')
I tried the append, replace and rename methods as well and it didn't work for me. or those don't work in the 1st place with what I am trying to do?
What am I missing or doing wrong?.
回答1:
You need os.rename. But before that,
Check to make sure they aren't folders (thanks, AGN Gazer)
Check to make sure those files don't have extensions already. You can do that with
os.path.splitext.
import os
root = os.getcwd()
for file in os.listdir('.'):
if not os.path.isfile(file):
continue
head, tail = os.path.splitext(file)
if not tail:
src = os.path.join(root, file)
dst = os.path.join(root, file + '.txt')
if not os.path.exists(dst): # check if the file doesn't exist
os.rename(src, dst)
来源:https://stackoverflow.com/questions/45540785/adding-extension-to-multiple-files-python3-5