I would like to change the extension of the files in specific folder. i read about this topic in the forum. using does ideas, I have written following code and I expect that it would work but it does not. I would be thankful for any guidance to find my mistake.
import os,sys
folder = 'E:/.../1936342-G/test'
for filename in os.listdir(folder):
infilename = os.path.join(folder,filename)
if not os.path.isfile(infilename): continue
oldbase = os.path.splitext(filename)
infile= open(infilename, 'r')
newname = infilename.replace('.grf', '.las')
output = os.rename(infilename, newname)
outfile = open(output,'w')
The open on the source file is unnecessary, since os.rename only needs the source and destination paths to get the job done. Moreover, os.rename always returns None, so it doesn't make sense to call open on its return value.
import os
import sys
folder = 'E:/.../1936342-G/test'
for filename in os.listdir(folder):
infilename = os.path.join(folder,filename)
if not os.path.isfile(infilename): continue
oldbase = os.path.splitext(filename)
newname = infilename.replace('.grf', '.las')
output = os.rename(infilename, newname)
I simply removed the two open. Check if this works for you.
You don't need to open the files to rename them, os.rename only needs their paths. Also consider using the glob module:
import glob, os
for filename in glob.iglob(os.path.join(folder, '*.grf')):
os.rename(filename, filename[:-4] + '.las')
Something like this will rename all files in the executing directory that end in .txt to .text
import os, sys
for filename in os.listdir(os.path.dirname(os.path.abspath(__file__))):
base_file, ext = os.path.splitext(filename)
if ext == ".txt":
os.rename(filename, base_file + ".text")
import os
dir =("C:\\Users\\jmathpal\\Desktop\\Jupyter\\Arista")
for i in os.listdir(dir):
files = os.path.join(dir,i)
split= os.path.splitext(files)
if split[1]=='.txt':
os.rename(files,split[0]+'.csv')
#!/usr/bin/env python
'''
Batch renames file's extension in a given directory
'''
import os
import sys
from os.path import join
from os.path import splitext
def main():
try:
work_dir, old_ext, new_ext = sys.argv[1:]
except ValueError:
sys.exit("Usage: {} directory old-ext new-ext".format(__file__))
for filename in os.listdir(work_dir):
if old_ext == splitext(filename)[1]:
newfile = filename.replace(old_ext, new_ext)
os.rename(join(work_dir, filename), join(work_dir, newfile))
if __name__ == '__main__':
main()
If you have python 3.4 or later, you can use pathlib. It is as follows. This example is for changing .txt to .md.
from pathlib import Path
path = Path('./dir')
for f in path.iterdir():
if f.is_file() and f.suffix in ['.txt']:
f.rename(f.with_suffix('.md'))
With print and validation.
import os
from os import walk
mypath = r"C:\Users\you\Desktop\test"
suffix = ".png"
replace_suffix = ".jpg"
filenames = next(walk(mypath), (None, None, []))[2]
for filename in filenames:
if suffix in filename:
print(filename)
rep = input('Press y to valid rename : ')
if rep == "y":
for filename in filenames:
if suffix in filename:
os.rename(mypath+"\\"+filename, mypath+"\\"+filename.replace(suffix, replace_suffix))
Related
I am trying to delete all xlsx files from a folder, note it has files of other extension. Given below is what I have tried:
path = '/users/user/folder'. <-- Folder that has all the files
list_ = []
for file_ in path:
fileList = glob.glob(path + "/*.xlsx")
fileList1 = " ".join(str(x) for x in fileList)
try:
os.remove(fileList1)
except Exception as e:
print(e)
But the above does not delete the xlsx files.
Try:
import os
import glob
path = '/users/user/folder'
for f in glob.iglob(path+'/**/*.xlsx', recursive=True):
os.remove(f)
you can use this code to delete the xlsx or xls file
import os
path = r'your path '
os.chdir(path)
for file in os.listdir(path):
if file.endswith('.xlsx') or file.endswith('.xls'):
print(file)
os.remove(file)
You can use the below code as well to remove multiple .xlsx files in a folder.
import glob, os
path =r"folder path"
filenames = glob.glob(path + "/*.xlsx")
for i in filenames:
os.remove(i)
It would be better to use os.listdir() and fnmatch.
Try the below code .
`import os, fnmatch
listOfFiles = os.listdir('/users/user/folder') #filepath
pattern = "*.xslx"
for entry in listOfFiles:
if fnmatch.fnmatch(entry, pattern):
print ("deleting"+entry)
os.remove(entry)`
I would like to change the extension of the files in specific folder. i read about this topic in the forum. using does ideas, I have written following code and I expect that it would work but it does not. I would be thankful for any guidance to find my mistake.
import os,sys
folder = 'E:/.../1936342-G/test'
for filename in os.listdir(folder):
infilename = os.path.join(folder,filename)
if not os.path.isfile(infilename): continue
oldbase = os.path.splitext(filename)
infile= open(infilename, 'r')
newname = infilename.replace('.grf', '.las')
output = os.rename(infilename, newname)
outfile = open(output,'w')
The open on the source file is unnecessary, since os.rename only needs the source and destination paths to get the job done. Moreover, os.rename always returns None, so it doesn't make sense to call open on its return value.
import os
import sys
folder = 'E:/.../1936342-G/test'
for filename in os.listdir(folder):
infilename = os.path.join(folder,filename)
if not os.path.isfile(infilename): continue
oldbase = os.path.splitext(filename)
newname = infilename.replace('.grf', '.las')
output = os.rename(infilename, newname)
I simply removed the two open. Check if this works for you.
You don't need to open the files to rename them, os.rename only needs their paths. Also consider using the glob module:
import glob, os
for filename in glob.iglob(os.path.join(folder, '*.grf')):
os.rename(filename, filename[:-4] + '.las')
Something like this will rename all files in the executing directory that end in .txt to .text
import os, sys
for filename in os.listdir(os.path.dirname(os.path.abspath(__file__))):
base_file, ext = os.path.splitext(filename)
if ext == ".txt":
os.rename(filename, base_file + ".text")
import os
dir =("C:\\Users\\jmathpal\\Desktop\\Jupyter\\Arista")
for i in os.listdir(dir):
files = os.path.join(dir,i)
split= os.path.splitext(files)
if split[1]=='.txt':
os.rename(files,split[0]+'.csv')
#!/usr/bin/env python
'''
Batch renames file's extension in a given directory
'''
import os
import sys
from os.path import join
from os.path import splitext
def main():
try:
work_dir, old_ext, new_ext = sys.argv[1:]
except ValueError:
sys.exit("Usage: {} directory old-ext new-ext".format(__file__))
for filename in os.listdir(work_dir):
if old_ext == splitext(filename)[1]:
newfile = filename.replace(old_ext, new_ext)
os.rename(join(work_dir, filename), join(work_dir, newfile))
if __name__ == '__main__':
main()
If you have python 3.4 or later, you can use pathlib. It is as follows. This example is for changing .txt to .md.
from pathlib import Path
path = Path('./dir')
for f in path.iterdir():
if f.is_file() and f.suffix in ['.txt']:
f.rename(f.with_suffix('.md'))
With print and validation.
import os
from os import walk
mypath = r"C:\Users\you\Desktop\test"
suffix = ".png"
replace_suffix = ".jpg"
filenames = next(walk(mypath), (None, None, []))[2]
for filename in filenames:
if suffix in filename:
print(filename)
rep = input('Press y to valid rename : ')
if rep == "y":
for filename in filenames:
if suffix in filename:
os.rename(mypath+"\\"+filename, mypath+"\\"+filename.replace(suffix, replace_suffix))
How can i apply a script for file modification in all subfolder (in python)?
I created a little script for rename some pictures but my program only change pictures in the script folder and not in subfolder.
from PIL import Image
from os import *
import sys
from os.path import basename
import os
#from PIL.ExifTags import TAGS
from datetime import datetime
extension = ''
#path='/home/pi/Desktop/testrename'
folder_path = "/home/pi/Desktop/testrename/"
l=[]
import PIL.Image
from os import walk
#from path import path
import glob
EXIF_DATETIME = 36867
def renamefinaljpeg() :
glob.glob ('*/.jpeg')
if len(fname) < 20 :
try :
old = PIL.Image.open(fname)._getexif()[EXIF_DATETIME]
old2 = old.split(' ')
os.rename (fname, "yes" + old2[0]+' '+fname)
print('fait')
except :
pass
print('pas jpeg')
def renamefinaljpg() :
glob.glob ('*/.jpg')
if len(fname) < 20 :
try :
old = PIL.Image.open(fname)._getexif()[EXIF_DATETIME]
old2 = old.split(' ')
os.rename (fname, "yes" + old2[0]+' '+fname)
print('fait')
except :
pass
print('pas jpg')
rootDir = "/home/pi/Desktop/testrename/"
for dirName, subdirlist, fileList in os.walk(rootDir) :
for fname in fileList :
print(fname)
try :
renamefinaljpg() or renamefinaljpeg()
except :
pass
print('passe')
The image are renamed in the main directory but not in directory tree (but they are read)
Thank you for your help.
It looks like you've already got a lot of ideas for how to do it in your script. Let's use os.walk since that's probably the most straightforward. os.walk will iterate over all of our directories recursively and give us the list of filenames contained in each one. To filter the files to only .jpg we can use fnmatch.fnmatch.
import fnmatch
import os
import sys
from PIL import Image
folder_path = '/home/pi/Desktop/testrename/old'
# Give special numbers a specific name so it's easier to remember what it
# actually means.
EXIF_DATETIME = 36867
def renamefinal(dir_path, filename):
try:
old = Image.open(file_path)._getexif()[EXIF_DATETIME]
date, time = old.split(' ', maxsplit=1)
new_filename = date + ' ' + filename
os.rename(
# Source file name, including directory and filename
os.path.join(dir_path, filename),
# Destination file name, including date
os.path.join(dir_path, new_filename))
print(
'jpg renommé ({}): {} to {}'.format(
dir_path, filename, new_filename))
except:
# Including filename in our output so we know what to check if
# something goes wrong.
print('pas jpg ({}): {}'.format(dir_path, filename))
for path, dirs, files in os.walk(folder_path):
for filename in files:
if not fnmatch.fnmatch(filename, '*.jpg'):
# Go to the next file, skipping the rest of the loop for this file.
continue
if 30 <= len(filename):
continue
renamefinal(path, filename)
Some more that might help:
If you want to take arguments to your script check out the argparse module.
Try to catch exceptions more specifically, for example using except KeyError: instead of except: when you know that EXIF_DATETIME may not be in the exif data - also try putting your try: ... except: ... block only around the lines that might actually fail.
Check out the logging module instead of using print to show information about what your script is doing.
I am having a difficult time creating a python script that will rename file extensions in a folder and continue to do so in sub directories. Here is the script I have thus far; it can only rename files in the top directory:
#!/usr/bin/python
# Usage: python rename_file_extensions.py
import os
import sys
for filename in os.listdir ("C:\\Users\\username\\Desktop\\test\\"): # parse through file list in the folder "test"
if filename.find(".jpg") > 0: # if an .jpg is found
newfilename = filename.replace(".jpg","jpeg") # convert .jpg to jpeg
os.rename(filename, newfilename) # rename the file
import os
import sys
directory = os.path.dirname(os.path.realpath(sys.argv[0])) #get the directory of your script
for subdir, dirs, files in os.walk(directory):
for filename in files:
if filename.find('.jpg') > 0:
subdirectoryPath = os.path.relpath(subdir, directory) #get the path to your subdirectory
filePath = os.path.join(subdirectoryPath, filename) #get the path to your file
newFilePath = filePath.replace(".jpg",".jpeg") #create the new name
os.rename(filePath, newFilePath) #rename your file
I modified Jaron's answer with the path to the file and the complete example of renaming the file
I modified the answer of Hector Rodriguez Jr. a little bit because it would replace ANY occurance of ".jpg" in the path, e.g. /path/to/my.jpg.files/001.jpg would become /path/to/my.jpeg.files/001.jpeg, which is not what you wanted, right?
Although it is generally not a good idea to use dots "." in a folder name, it can happen...
import os
import sys
directory = os.path.dirname(os.path.realpath(sys.argv[0])) # directory of your script
for subdir, dirs, files in os.walk(directory):
for filename in files:
if filename.find('.jpg') > 0:
newFilename = filename.replace(".jpg", ".jpeg") # replace only in filename
subdirectoryPath = os.path.relpath(subdir, directory) # path to subdirectory
filePath = os.path.join(subdirectoryPath, filename) # path to file
newFilePath = os.path.join(subdirectoryPath, newFilename) # new path
os.rename(filePath, newFilePath) # rename
You can process the directory like this:
import os
def process_directory(root):
for item in os.listdir(root):
if os.path.isdir(item):
print("is directory", item)
process_directory(item)
else:
print(item)
#Do stuff
process_directory(os.getcwd())
Although, this isn't really necessary. Simply use os.walk which will iterate through all toplevel and further directories / files
Do it like this:
for subdir, dirs, files in os.walk(root):
for f in files:
if f.find('.jpg') > 0:
#The rest of your stuff
That should do exactly what you want.
i have a folder with a lot of files like that:
2012-05-09.txt
2012-05-10.txt
2012-05-11.txt
etc.
now i wanna delete the hyphen and add " _PHOTOS_LOG " that it looks in the end like this:
20120509_PHOTOS_LOG.txt
20120510_PHOTOS_LOG.txt
20120511_PHOTOS_LOG.txt
etc.
How to do ?
thats the code now:
//updated the code, now its working
import os
import glob
import os.path
import sys
src = 'D:\\testing/hyphen1'
src = r'D:\testing\test'
for fn in os.listdir(src):
new_filename = fn.replace('-','').replace('.txt', '_PHOTOS_LOG.txt')
fn = os.path.join(src, fn)
new_filename = os.path.join(src, new_filename)
try:
os.rename(fn, new_filename)
except (WindowsError, OSError):
print 'Error renaming "%s" to "%s"' % (fn, new_filename)
print sys.exc_info()[1]
You could do the rename something like this:
import os
for filename in os.listdir("."):
if filename.endswith(".txt"):
newFilename = filename.replace("-", "")
os.rename(filename, newFilename[:7]+"_PHOTO_LOG.txt")
os.listdir(".") returns the names of the entries in the current folder
filename.endswith(".txt") verifies if the filename is one of your text files
if it is, it removes the - and adds the _PHOTO_LOG at the end
new_filename = old_filename.replace("-", "").replace(".txt", "_PHOTOS_LOG.txt")
That will get you the new filename, if you want to rename all the files, then:
import os
for old_filename in os.listdir("."):
new_filename = old_filename.replace("-", "").replace(".txt", "_PHOTOS_LOG.txt")
os.rename(old_filename, new_filename)
For all of your files in your current directory:
import os
for fn in os.listdir('.'):
new_filename = fn.replace('-','').replace('.txt', '_PHOTOS_LOG.txt')
os.rename(fn, new_filename)
Using os.rename() to change the filenames.
The individual file names will end up a series of strings, so while you usually would want to use methods from the os module, you can simply treat these as strings since you are not looking at paths, but simple filenames and use replace() to create the new names.
--
Example for one filename to show transformation:
fn ='2012-05-09.txt'
then
fn.replace('-','').replace('.txt', '_PHOTOS_LOG.txt')
will yield '20120509_PHOTOS_LOG.txt'
You need to iterate through the list of files
and rename them according to your needs:
import os
import glob
for name in glob.glob('*.txt'):
newname = "%s_PHOTOS_LOG.txt" % name.replace('-','')[:-4]
os.rename(name, newname)
The glob.glob function produces a list of .txt files in the current directory.