I've just run this script to rename my files, adding the 15 first chars of files, but now all the files are disappearead, and i can't find them. i've just run this on a mac
import os
def replace(folder_path, old, new):
for path, subdirs, files in os.walk(folder_path):
for name in files:
file_path = os.path.join(path,name)
new_name = os.path.basename(path)[:15] + " - " + name
print path + "##" + new_name
os.rename(file_path, new_name)
replace('/Users/myuser/mp3/', '', '')
#DDave,
In the function call os.rename(src, dst): src is the fully qualified filepath of the source file, and dst is fully qualified filepath of the target file.
In your above program, new_name is just the new name of the file which does not have the directory information (and hence it is considering the directory as your current working directory). That is why you are not seeing the renamed files where you were looking to see them.
The program is rather trying to create the files under your current working directory. Run the following from your console of your IDE or from your program to figure out the current working directory:
print(os.getcwd())
Providing the full solution as requested in the comment below:
import os
def replace(folder_path, old, new):
for path, subdirs, files in os.walk(folder_path):
for name in files:
file_path = os.path.join(path,name)
# new_name = os.path.basename(path)[:15] + " - " + name
new_filepath = os.path.join(path, (name[:15] if len(name)>=15 else name) + " - " + name)
print ("new path: " + new_filepath)
os.rename(file_path, new_filepath)
Related
I have folders like this
in each folder, it contains file like this :
i want to move every file with the name "Indeks-Standar-Pencemar-Udara-di-SPKU-Bulan*" in each folder to one designated folder, i try this code but nothing happened
target_folder = r"C:\Users\EVOSYS\Documents\PROJECT-ISPU-DKI-JAKARTA-main\File Gabungan ISPU di SPKU 2010 - 2021" + "\\"
source_folder = r"C:\Users\EVOSYS\Documents\PROJECT-ISPU-DKI-JAKARTA-main" + "\\"
for path, dir, files in os.walk(source_folder):
if files:
for file in files:
if not os.path.isfile(target_folder + file):
if "Indeks-Standar-Pencemar-Udara-di-SPKU-Bulan*" in file:
os.rename(path + '\\' + file, target_folder + file)
I'm working with Python and I'd like to copy 3 files of a certain folder
/Users/jake/Desktop/exp to all the subfolders of other sub-directories belonging to the directory /toyspace:
/Users/jake/Desktop/toyspace/1A/AAA
/Users/jake/Desktop/toyspace/1A/BBB
/Users/jake/Desktop/toyspace/1A/CCC
/Users/jake/Desktop/toyspace/2B/AAA
/Users/jake/Desktop/toyspace/2B/BBB
/Users/jake/Desktop/toyspace/2B/CCC
So the subfolders names are the same for all the sub-directories. I wrote something like that:
from distutils.dir_util import copy_tree
def myfunc (source, destination):
fromDirectory = source
toDirectory = destination
copy_tree(fromDirectory, toDirectory)
for subfold in toDirectory:
myfunc(fromDirectory, subfold)
Where source =/Users/jake/Desktop/exp and destination =/Users/jake/Desktop/toyspace, but it returns me an error:
DistutilsFileError: could not create '/motif_list.txt': Read-only file system
Can you help me? Thanks in advance!
Unfortunately I have not used distutils but you can try to automate using the os command as below
import os
def copy_folders(source_dir, destination_dir):
files = os.listdir(source_dir)
for sub_folder1 in os.listdir(destination_dir):
for sub_folder in os.listdir(destination_dir + sub_folder1 + '/'):
for file in files:
os.system('cp ' + source_dir + file + ' ' + destination_dir + sub_folder1 + '/' + sub_folder + '/')
Let me know how it goes :)
I am trying to copy all jpeg files from a directory (with multiple subdirectories) to a single directory. There are multiple files with the same name, so I am trying to rename the files using the name of the parent directory. For example: c:\images\tiger\image_00001.jpg will be moved to a new folder and renamed to c:\images\allimages\tiger_image_00001.jpg. I tried the code below, but nothing happens. The folder gets created, but the files do not move. This is what I have so far:
import os
path = 'source/'
os.mkdir('source/allimages/')
extensions = ['.jpeg']
for folder, _, filenames in os.walk(path):
for filename in filenames:
if folder == path or folder == os.path.join(path, 'allimages'):
continue
folder = folder.strip(path)
extension = os.path.splitext(os.path.splitext(filename)[0])[-1].lower()
if extension in extensions:
infilename = os.path.join(path, folder, filename)
newname = os.path.join(path, 'all_files', "{}-{}".format(folder.strip('./')))
os.rename(infilename, newname)
I would recommend having a function dedicated to resolving a unique filename. A while loop should do the trick. This should work.
import os
import shutil
def resolve_path(filename, destination_dir):
dest = os.path.join(destination_dir, filename)
*base_parts, extension = filename.split('.')
base_name = '.'.join(base_parts)
duplicate_num = 1
while os.path.exists(dest):
new_base = base_name + str(duplicate_num).zfill(5)
new_filename = "{}.{}".format(new_base, extension)
dest = os.path.join(destination_dir, new_filename)
duplicate_num += 1
return dest
That is such that the following is the result....
>>> with open('/path/to/file.extension', 'w') as f:
>>> pass # just create the file
>>> resolve_path('file.extension', '/path/to/')
'/path/to/file00001.extension'
Then put it together with traversing the source...
def consolidate(source, destination, extension='.jpg'):
if not os.path.exists(destination):
os.makedirs(destination)
for root, dirs, files in os.walk(source):
for f in files:
if f.lower().endswith(extension):
source_path = os.path.join(root, f)
destination_path = resolve_path(f, destination)
shutil.copyfile(source_path, destination_path)
You're calling splitext on its own output, which doesn't get what you want:
In [4]: os.path.splitext(os.path.splitext('foo.bar')[0])[-1]
Out[4]: ''
You just want extension = os.path.splitext(filename)[-1].lower(), or if you don't want the dot, then extension = os.path.splitext(filename)[-1].lower()[1:].
(Edited) more seriously, there's a problem with folder.strip(path): this will remove all characters in path from folder. For instance 'source/rescue'.strip('source/') == ''. What you want is folder.replace(path, '').
I recovered from a fully functioning server(Windows Server R2-2012) from my backup, and instead of overwriting the existing files, it created copies of all the files in my server.
I wrote a python(3.5.2) script to delete the files that has the name "2017-09-09 00-00 Copy of_Filename" but it still doesn't delete few files.
My folders and sub-directories have "full control" for the account I signed in with. I am manually able to delete the files, but my script or batch file couldn't. The error I'm getting is "permission denied"
I have run my batch file in administrative mode as well, but still no effect.
Python(3.5.2) script:
import os
import re
import fnmatch
f = open("log.txt","w+")
count = 1
for root, dirs, files in os.walk("c:\\Website\\",topdown=False):
for fl in files:
if re.match('2017-09-09 00-00 Copy of',fl ):
try:
file_path = os.path.join(root, fl)
os.remove(file_path)
print("Deleting file " + file_path)
except:
file_path = os.path.join(root, fl)
f.write(str(count) + " " + file_path + "\n")
#print(str(count) + " " + file_path + "\n")
count+=1
f.close()
This is an example of the folder contents that I am trying to delete 1.
This is the access status of the folder. I am "Administrator"
2
I feel my server(IIS) is not running due to this error.
Any help is appreciated.
I am learning Python and I have been tasked with:
adding "file_" to the beginning of each name in a directory
changing the extension (directory contains 4 different types currently: .py, .TEXT, .rtf, .text)
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:
the script currently must be inside my directory for it to run.
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.
import glob, os
path = 'test/'# your path
extensions = ['.rtf', '.py', '.TEXT', '.text']
for file in glob.glob(os.path.join(path, '*.*')):
file_path, extension = os.path.splitext(file)
if extension in extensions:
new_file_name = '{0}.txt'.format(
os.path.basename(file_path)
)
if not new_file_name.startswith('file_'): # check if file allready has 'file_' at beginning
new_file_name = 'file_{0}'.format( # if not add
new_file_name
)
new_file = os.path.join(
os.path.dirname(file_path),
new_file_name
)
os.rename(file, new_file)
file_path, extension = os.path.splitext(file) getting file path without extension and extension f.e ('dir_name/file_name_without_extension','.extension')
os.path.dirname(file_path) getting directory f.e if file_path is dir1/dir2/file.ext result will be 'dir1/dir2'
os.path.basename(file_path) getting file name without extension
import os, sys
path = 'data' // Initial path
def changeFileName( path, oldExtensions, newExtension ):
for name in os.listdir(path):
for oldExtension in oldExtensions:
if name.endswith(oldExtension):
name = os.path.join(path, name)
newName = name.replace(oldExtension, newExtension)
os.rename(name, newName)
break;
if __name__ == "__main__":
changeFileName( 'data', ['.py', '.rtf' , '.text', '.TEXT'], '.txt')
Use an array to store all the old extensions and iterate through them.