I have a large directory structure, each directory containing multiple sub-directories, multiple .mbox files, or both. I need to rename all the .mbox files to the respective file name without the extension e.g.
bar.mbox -> bar
foo.mbox -> foo
Here is the script I've written:
# !/usr/bin/python
import os, sys
def walktree(top, callback):
for path, dirs, files in os.walk(top):
for filename in files:
fullPath = os.path.join(path, filename)
callback(fullPath)
def renameFile(file):
if file.endswith('.mbox'):
fileName, fileExt = os.path.splitext(file)
print file, "->", fileName
os.rename(file,fileName)
if __name__ == '__main__':
walktree(sys.argv[1], renameFile)
When I run this using:
python walktrough.py "directory"
I get the error:
Traceback (most recent call last):
File "./walkthrough.py", line 18, in <module>
walktree(sys.argv[1], renameFile)
File "./walkthrough.py", line 9, in walktree
callback(fullPath)
File "./walkthrough.py", line 15, in renameFile
os.rename(file,fileName)
OSError: [Errno 21] Is a directory
This was solved by adding an extra conditional statement to test if the name the file was to be changed to, was a current directory.
If this was true, the filename to-be had an underscore added to.
Thanks to WKPlus for the hint on this.
BCvery1
Related
I am writing a python script to rename all files in a given folder. The python script exists in my j-l-classifier along with images/jaguar file. I'm trying to run the following script to take each file in the folder and rename it to this format:
jaguar_[#].jpg
But its throwing the following error:
Traceback (most recent call last):
File "/home/onur/jaguar-leopard-classifier/file.py", line 14, in <module>
main()
File "/home/onur/jaguar-leopard-classifier/file.py", line 9, in main
os.rename(filename, "Jaguar_" + str(x) + file_ext)
FileNotFoundError: [Errno 2] No such file or directory: '406.Black+Leopard+Best+Shot.jpg' -> 'Jaguar_0.jpg'
This is my code:
import os
def main():
x = 0
file_ext = ".jpg"
for filename in os.listdir("images/jaguar"):
os.rename(filename, "Jaguar_" + str(x) + file_ext)
x += 1
if __name__ == '__main__':
main()
In order to use os.rename(), you need to provide absolute paths.
I would suggest replacing line 9 with os.rename(os.path.expanduser(f"~/{whatever folders you have here}/images/jaguar/{filename}"), os.path.expanduser(f"~/{whatever folders you have here}/images/jaguar/Jaguar_{str(x)}{file_ext}")
os.path.expanduser() allows you to use the "~" syntax to aid the abs file path.
os.listdir only returns the filename (not the file path...)
try the following
for filename in os.listdir("images/jaguar"):
filepath = os.path.join("images/jaguar",filename)
new_filepath = os.path.join("images/jaguar","Jaguar_{0}{1}".format(x,file_ext))
os.rename(filepath, new_filepath)
being explicit is almost always a path to a happier life
I intent to move files in the current directory('~/Documents/') as a.py b.py c.py to destination file '~/Desktop'.
import os
import glob
path = '~/Documents/'
os.chdir(path)
destination_path = '~/Desktop'
Next step to attain the files
file = glob.glob(path + '*.py')
source_files = file[:]
Set the Command
cmd = 'mv %s %s'
Iterate the files
for file in source_files:
os.open(cmd %(file, destination_path))
Error reports
Traceback (most recent call last):
File "move-files.py", line 14, in <module>
os.open(cmd %(file, destination_path))
TypeError: Required argument 'flags' (pos 2) not found
I tried to apply eval on cmd and other operatons to solve the errors.
How to move files with 'pipes' elegently?
for file in source_files:
os.open(cmd %(file, destination_path)) # misuse os.popen()
Basically I have got it all done. But when actually trying to rename the files I get the error
Traceback (most recent call last):
File
"C:\Users\CHOMAN\Desktop\Earthquake_1_combine_3_jan\Earthquake_1_combine\wav\sort_inner_wav.py", line 21, in <module>
os.rename(file, new_name)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Audio Track-10.wav' -> 'choman_10.wav'
Up until the last print statement the values are correct. Not sure how to rename it. Under wav folder there are 32 sub folder which has around 10 .wav files in it.
import os
rootdir = r'C:\Users\CHOMAN\Desktop\Earthquake_1_combine_3_jan\Earthquake_1_combine\wav'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
filepath = subdir+os.sep+file
if filepath.endswith('.wav'):
f_name, f_ext=(os.path.splitext(file))
if len(f_name) == 11:
f_name = f_name+'-0'
f_title,f_num =f_name.split('-')
f_num=f_num.zfill(2)
new_name = '{}_{}{}'.format('choman',f_num,f_ext)
print (file, new_name)
os.rename(file, new_name)
All you need is:
os.rename(filepath, subdir+os.sep+new_name)
That's because you need the full path.
If you are not running this script under the same location as 'rootdir' and there are sub directories, you need to specify the absolute path of source file and destination file. Otherwise, the file would not be found.
# python 2.7
os.rename(filepath, os.path.join(subdir, new_name))
# python >= 3.3
os.rename(file, new_name, subdir, subdir)
I have a simple code to zip files using zipfile module. I am able to zip some files but I get FileNotFound error for the others. I have checked if this is file size error but its not.
I can pack files with name like example file.py but when I have a file inside a directory like 'Analyze Files en-US_es-ES.xlsx' if fails.
It works when I change os.path.basename to os.path.join but I don't want to zip whole folder structure, I want to have flat structure in my zip.
Here is my code:
import os
import zipfile
path = input()
x=zipfile.ZipFile('new.zip', 'w')
for root, dir, files in os.walk(path):
for eachFile in files:
x.write(os.path.basename(eachFile))
x.close()
Error looks like this:
Traceback (most recent call last):
File "C:/Users/mypc/Desktop/Zip test.py", line 15, in <module>
x.write(os.path.basename(eachFile))
File "C:\Python34\lib\zipfile.py", line 1326, in write
st = os.stat(filename)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Analyze Files en-US_ar-SA.xlsx'*
Simply change working directory to add file without original directory structure.
import os
import zipfile
path = input()
baseDir = os.getcwd()
with zipfile.ZipFile('new.zip', 'w') as z:
for root, dir, files in os.walk(path):
os.chdir(root)
for eachFile in files:
z.write(eachFile)
os.chdir(baseDir)
I have a folder with a few files that I would like to copy one directory up (this folder also has some files that I don't want to copy). I know there is the os.chdir("..") command to move me to the directory. However, I'm not sure how to copy those files I need into this directory. Any help would be greatly appreciated.
UPDATE:
This is what I have now:
from shutil import copytree, ignore_patterns
copytree("/Users/aaron/Desktop/test/", "/Users/aaron/Desktop/", ignore=ignore_patterns('*.py', '*.txt'))
I am getting the following error:
Traceback (most recent call last):
File "update.py", line 61, in <module>
copytree("/Users/aaron/Desktop/test/", "/Users/aaron/Desktop/", ignore=ignore_patterns('*.py', '*.txt'))
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/shutil.py", line 146, in copytree
os.makedirs(dst)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/os.py", line 157, in makedirs
mkdir(name, mode)
OSError: [Errno 17] File exists: '/Users/aaron/Desktop/'
The shutil module can do this, specifically the copyfile, copy, copy2 and copytree functions. http://docs.python.org/library/shutil.html
You probably want something along these lines:
import os
import shutil
fileList = os.listdir('path/to/source_dir')
fileList = ['path/to/source_dir/'+filename for filename in fileList]
for f in fileList:
shutil.copy2(f, 'path/to/dest_dir/')
You can of course filter some file names out during the call to os.listdir(). For example,
fileList = [filename for filename in os.listdir('path/to/source_dir') if filename[-3] is '.txt']
instead of fileList = os.listdir('path/to/source_dir') to get just the .txt files