Renaming all the files in folders within directory - python

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)

Related

Unable to open or read log files: FileNotFoundError [duplicate]

I'm trying to run the following script which simply reads and image and saves it again:
from PIL import Image
import os
rootdir = '/home/user/Desktop/sample'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
im = Image.open(file)
im.save(file)
I however get the following error:
Traceback (most recent call last):
File "test.py", line 10, in <module>
im = Image.open(file)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 2258, in open
fp = builtins.open(filename, "rb")
IOError: [Errno 2] No such file or directory: '1.jpg'
So, what I'm trying to do is simply read the file 1.jpg and save it again, provided that 1.jpg is located in the directory.
How can I fix this issue?
Thanks.
You're going to need to provide a fully qualified path, because file holds only the tail, not the entire path.
You can use os.path.join to join the root to the tail:
for root, dirs, files in os.walk(rootdir):
for file in files:
path = os.path.join(root, file)
im = Image.open(path)
im.save(path)

FileNotFoundError when trying to rename all the files in a directory

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

IOError on opening a csv file

I wanted to loop through a file. I can get it and I can print its location but I keep getting IOError!
import os, sys
directory = sys.argv[1]
for root, dirs, files in os.walk(directory):
if len(files) >= 3:
for f in files:
print(os.path.join(root, f))
if f.endswith(".csv"):
print f + " made it this far"
with open(os.path.join(directory, f), "r") as d:
for line in d:
print "hello"
my readout..
/Users/eeamesX/work/data/GERMANY/DE_023/continuous/2015-06-01#ab6686a5-c733-4055-a15e-b28b9705b6ca/2015-06-01#ab6686a5-c733-4055-a15e-b28b9705b6ca.wav
/Users/eeamesX/work/data/GERMANY/DE_023/continuous/2015-06-01#ab6686a5-c733-4055-a15e-b28b9705b6ca/2015-06-01#ab6686a5-c733-4055-a15e-b28b9705b6ca.xml
/Users/eeamesX/work/data/GERMANY/DE_023/continuous/2015-06-01#ab6686a5-c733-4055-a15e-b28b9705b6ca/2015-06-01#ab6686a5-c733-4055-a15e-b28b9705b6ca_edited.xml
/Users/eeamesX/work/data/GERMANY/DE_023/continuous/2015-06-01#ab6686a5-c733-4055-a15e-b28b9705b6ca/foo.csv
foo.csv made it this far
Traceback (most recent call last):
File "findFiles.py", line 16, in <module>
with open(os.path.join(directory, f), "r") as d:
IOError: [Errno 2] No such file or directory: '/Users/eeamesX/work/data/GERMANY/DE_023/continuous/foo.csv'
The problem is that directory is the point from which you start traversing the filesystem. When you do for root, dirs, files in os.walk(directory), you get the current directory as root, a list of the subdirectories it contains in dirs, and a list of the files it contains in files. Therefore, if you join directory with f, you will end up searching for f in the directory where you started your file system traversal. Such a file likely does not exist in that starting location
Rather, you want to open the file contained in the directory within which it is contained (i.e. root). Therefore, you should os.path.join(root, f) to get the correct file path

Python zipfile crashes gives an error for some files

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)

Renaming files recursively with Python

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

Categories

Resources