Renaming OS files - python

I am trying to rename files based on their extensions. Below is my code, Somehow my os.rename isn't working. There aren't any errors though. I got no idea what is wrong. Hope you guys could help. Thanks.
import os
import glob
directory = raw_input("directory? ")
ext = raw_input("file extension? ")
r = raw_input("replace name")
pattern = os.path.join(directory, "*" + ext)
matching_files = glob.glob(pattern)
file_number = len(matching_files)
for filename in os.listdir(directory):
if ext in filename:
path = os.path.join(directory, filename)
seperated_names = os.path.splitext(filename)[0]
replace_name = filename.replace(seperated_names, r)
split_new_names = os.path.splitext(replace_name)[0]
for pad_number in range(0, file_number):
padded_numbers = "%04d" % pad_number
padded_names = "%s_%s" % (split_new_names, padded_numbers)
newpath = os.path.join(directory, padded_names)
newpathext = "%s%s" % (newpath, ext)
new_name = os.rename(path, newpathext)

I get an error:
directory? c:\breakup
file extension? .txt
replace name? test
Traceback (most recent call last):
File "foo.py", line 25, in <module>
new_name = os.rename(path, newpathext)
WindowsError: [Error 2] The system cannot find the file specified
shell returned 1
Anyhow, it looks like you're over complicating things. This works just fine:
import os
directory = raw_input("directory? ")
ext = raw_input("file extension? ")
r = raw_input("replace name? ")
for i, filename in enumerate(os.listdir(directory)):
if filename.endswith(ext):
oldname = os.path.join(directory, filename)
newname = os.path.join(directory, "%s_%04d%s" % (r, i, ext))
os.rename(oldname, newname)

Related

File has moved to other folder. But I can't rename it in spyder

import os
import shutil
src_folder = r"C:\new1\\"
dst_folder = r"C:\new2\\"
file_name = 'testword.docx'
if os.path.exists(dst_folder + file_name):
data = os.path.splitext(file_name)
only_name = data[0]
extension = data[1]
new_base = only_name + 'Renamed' + extension
new_name = os.path.join(dst_folder, new_base)
shutil.move(src_folder + file_name, new_name)
else:
shutil.move(src_folder + file_name, dst_folder + file_name)
I was trying to write a code to move a file from one folder to another and rename it. The file is moving to another folder, But I can't rename it. I am doing this using python(spyder). Can anyone help me with this.

How to replace the name of several files in a folder by names on a text list

I have to change the name of several files in a folder such as:
CO201_LF.ab1
CO202_LF.ab1
CO034_LF.ab1
CO9871_LF.ab1
CO9576_LF.ab1
And replace those names with the names that I have in a list in a txt file.
How I can do that?
For the moment I have tried this without good results:
import os, fnmatch
def change_name():
file_path = '/home/SCRIPT_BIO/thesis_CSU/rbcL_LF_consolidated/ab1_RAW/'>
files_to_rename = fnmatch.filter(os.listdir(file_path), '*.ab1')
print(files_to_rename)
new_name = '/home/SCRIPT_BIO/thesis_CSU/rbcL_LF_consolidated/ab1_RAW/spp_list.txt/'>
for i, file_name in enumerate(files_to_rename):
new_file_name = new_name + str(i) + '.ab1'
os.rename(file_path + file_name,
file_path + new_file_name)
if __name__ == '__main__':
change_name()
The message that I have gotten is this:
"FileNotFoundError: [Errno 2] No such file or directory: '/home/SCRIPT_BIO/thesis_CSU/rbcL_LF_consolidated/ab1_RAW/CO201_LF.ab1' -> '/home/SCRIPT_BIO/thesis_CSU/rbcL_LF_consolidated/ab1_RAW//home/SCRIPT_BIO/thesis_CSU/rbcL_LF_consolidated/ab1_RAW/spp_list.txt0'"
What I want to get or the final product that I expect to get are those files (CO201_LF.ab1, etc.) renamed by the names in that list (spp_list.txt) in the same order.
Aegiphylla monica.ab1
Eugenia edulis.ab1
Miconia sparata.ab1
Deutemia claricia.ab1
Drapteris lineata,ab1
Maybe someone can help me?
Indent the os.rename() to be part of the "for" loop.
def change_name():
file_path = '/home/SCRIPT_BIO/thesis_CSU/rbcL_LF_consolidated/ab1_RAW/'>
files_to_rename = fnmatch.filter(os.listdir(file_path), '*.ab1')
print(files_to_rename)
new_name = '/home/SCRIPT_BIO/thesis_CSU/rbcL_LF_consolidated/ab1_RAW/spp_list.txt/'>
for i, file_name in enumerate(files_to_rename):
new_file_name = new_name + str(i) + '.ab1'
os.rename(file_path + file_name,
file_path + new_file_name)
if __name__ == '__main__':
change_name()

How to rename files after being copied based on creation time?

After copying files from a user provided source and destination, the files need to be renamed based on the creation time. The files have multiple extension types that need to be preserved while being renamed and a record original filenames. The issue arises when attempting to rename the file after it has been copied to the destination. All attempted solutions creates an exception in callback. What's the best approach here?
def filter_copy(self):
current_dir = self.Source.get()
destination_dir = self.Destination.get()
extensions = (['.avi', '.mpg'])
os.chdir(current_dir)
for root, dir, files in os.walk('.'):
for file in files:
if os.path.splitext(file)[1] in extensions:
src = os.path.join(root, file)
time.sleep(0.1)
logging.info("Copying the file %s..." % file)
print("Copying the file %s..." % file)
try:
with open('OriginalFilesReceipt.txt', 'w') as f:
f.write(file)
except FileNotFoundError:
logging.info("The directory does not exist to create to generate a receipt")
shutil.copy(src, destination_dir)
for names in os.listdir('.'):
t = os.path.getmtime(names)
v = datetime.datetime.fromtimestamp(t)
x = v.strftime('%Y%m%d-%H%M%S')
os.rename(names, x)
Found a solution based on the work from yzhong52 here: https://gist.github.com/tvdsluijs/1640613a32416b1197fc36b45e7b4999
The main error that was being received should have been obvious. The working directory wasn't the destination directory. The solution for the original question:
os.chdir(destination_dir)
for names in os.listdir('.'):
#split into filename and extension
filename, extension = os.path.splitext(names)
if (extension in extensions):
create_time = os.path.getctime(names)
format_time = datetime.datetime.fromtimestamp(create_time)
format_time_string = format_time.strftime("%Y-%m-%d %H.%M.%S")
newfile = format_time_string + extension
#if other file with same timestamp
if(newfile in newfilesDictionary.keys()):
index = newfilesDictionary[newfile] + 1
newfilesDictionary[newfile] = index
newfile = format_time_string + '-' + str(index) + extension
else:
newfilesDictionary[newfile] = 0
os.rename(names, newfile)
num_files = num_files + 1
print(names.rjust(35) + ' => ' + newfile.ljust(35))

How to create an extension for a file without extension in Python

I have a folder with a list of files without extensions, I need to rename or create an extension to each file ".text"
This is my code, but there is a small bug, the second time I run the code the files renamed again with a long name ,, for example
The file name : XXA
after first run : XXA.text
second : XXAXXA.text.text
import os
def renamefiles():
filelist = os.listdir(r"D:\")
print(filelist)
os.chdir(r"D:\")
path = os.getcwd()
for filename in filelist:
print("Old Name - "+filename)
(prefix, sep, sffix) = filename.rpartition(".")
newfile = prefix + filename + '.text'
os.rename(filename, newfile)
print("New Name - "+newfile)
os.chdir(path)
rename_files()
Where you have
newfile = prefix + '.text'
You can have
if not file_name.contains(".text"):
newfile = prefix + file_name + '.text'
Note where you have newfile = prefix + file_name + '.text', I changed it to newfile = prefix + '.text'. If you think about it, you don't need filename when you have already extracted the actual file name into prefix.
for file in os.listdir(os.curdir):
name, ext = os.path.splitext(file)
os.rename(file, name + ".text")
Don't do the partitioning that way, use os.path.splitext:
file_name, extension = os.path.splitext(filename)
if not extension:
newfile = file_name + '.text'
os.rename(filename, newfile)
If the file has no extension splitext returns '' which is Falsy. The file extension can then be changed.
import os
def renamefiles():
filelist = os.listdir(r"D:\")
print(filelist)
os.chdir(r"D:\")
path = os.getcwd()
for filename in filelist:
print("Old Name - "+filename)
(prefix, sep, sffix) = filename.rpartition(".")
newfile = prefix + filename + '.text'
if not filename.endswith(".text"):
os.rename(filename, newfile)
print("New Name - "+newfile)
os.chdir(path)
renamefiles()
You need to check if the filename ends with .text, and skip those

How to unzip a file with Python 2.4?

I'm having a hard time figuring out how to unzip a zip file with 2.4. extract() is not included in 2.4. I'm restricted to using 2.4.4 on my server.
Can someone please provide a simple code example?
You have to use namelist() and extract(). Sample considering directories
import zipfile
import os.path
import os
zfile = zipfile.ZipFile("test.zip")
for name in zfile.namelist():
(dirname, filename) = os.path.split(name)
print "Decompressing " + filename + " on " + dirname
if not os.path.exists(dirname):
os.makedirs(dirname)
zfile.extract(name, dirname)
There's some problem with Vinko's answer (at least when I run it). I got:
IOError: [Errno 13] Permission denied: '01org-webapps-countingbeads-422c4e1/'
Here's how to solve it:
# unzip a file
def unzip(path):
zfile = zipfile.ZipFile(path)
for name in zfile.namelist():
(dirname, filename) = os.path.split(name)
if filename == '':
# directory
if not os.path.exists(dirname):
os.mkdir(dirname)
else:
# file
fd = open(name, 'w')
fd.write(zfile.read(name))
fd.close()
zfile.close()
Modifying Ovilia's answer so that you can specify the destination directory as well:
def unzip(zipFilePath, destDir):
zfile = zipfile.ZipFile(zipFilePath)
for name in zfile.namelist():
(dirName, fileName) = os.path.split(name)
if fileName == '':
# directory
newDir = destDir + '/' + dirName
if not os.path.exists(newDir):
os.mkdir(newDir)
else:
# file
fd = open(destDir + '/' + name, 'wb')
fd.write(zfile.read(name))
fd.close()
zfile.close()
Not fully tested, but it should be okay:
import os
from zipfile import ZipFile, ZipInfo
class ZipCompat(ZipFile):
def __init__(self, *args, **kwargs):
ZipFile.__init__(self, *args, **kwargs)
def extract(self, member, path=None, pwd=None):
if not isinstance(member, ZipInfo):
member = self.getinfo(member)
if path is None:
path = os.getcwd()
return self._extract_member(member, path)
def extractall(self, path=None, members=None, pwd=None):
if members is None:
members = self.namelist()
for zipinfo in members:
self.extract(zipinfo, path)
def _extract_member(self, member, targetpath):
if (targetpath[-1:] in (os.path.sep, os.path.altsep)
and len(os.path.splitdrive(targetpath)[1]) > 1):
targetpath = targetpath[:-1]
if member.filename[0] == '/':
targetpath = os.path.join(targetpath, member.filename[1:])
else:
targetpath = os.path.join(targetpath, member.filename)
targetpath = os.path.normpath(targetpath)
upperdirs = os.path.dirname(targetpath)
if upperdirs and not os.path.exists(upperdirs):
os.makedirs(upperdirs)
if member.filename[-1] == '/':
if not os.path.isdir(targetpath):
os.mkdir(targetpath)
return targetpath
target = file(targetpath, "wb")
try:
target.write(self.read(member.filename))
finally:
target.close()
return targetpath
I am testing in Python 2.7.3rc2 and the the ZipFile.namelist() is not returning an entry with just the sub directory name for creating a sub directory, but only a list of file names with sub directory, as follows:
['20130923104558/control.json', '20130923104558/test.csv']
Thus the check
if fileName == '':
does not evaluate to True at all.
So I modified the code to check if the dirName exists inside destDir and to create dirName if it does not exist. File is extracted only if fileName part is not empty. So this should take care of the condition where a directory name can appear in ZipFile.namelist()
def unzip(zipFilePath, destDir):
zfile = zipfile.ZipFile(zipFilePath)
for name in zfile.namelist():
(dirName, fileName) = os.path.split(name)
# Check if the directory exisits
newDir = destDir + '/' + dirName
if not os.path.exists(newDir):
os.mkdir(newDir)
if not fileName == '':
# file
fd = open(destDir + '/' + name, 'wb')
fd.write(zfile.read(name))
fd.close()
zfile.close()

Categories

Resources