This question already has an answer here:
How to rename files using os.walk()?
(1 answer)
Closed 5 years ago.
I'm trying to rename a directory in Python, such hat the directory will be renamed to its first 8 characters of its original name.
This is what I did:
import os
path = '/home/directories'
for root, dirs, files in os.walk(path):
for directory in dirs:
new_name = directory[0:8]
os.rename(directory, new_name)
I however get the following error:
Traceback (most recent call last):
File "xyz.py", line 8, in <module>
os.rename(directory, new_name)
OSError: [Errno 2] No such file or directory
How can I solve this error?
Thanks.
You need to specify full path of directory
import os
path = 'C:\\Users\\demo_test_eg'
for root, dirs, files in os.walk(path):
for directory in dirs:
new_name = directory[0:8]
path1 = path + "\\"+ directory#Full path of directory
new_path = path + "\\"+new_name#Full path of file whose name is changed
os.rename(path1, new_path)
Note :
I have added "\\" for windows
Related
I tried making an python script which gets all directorys then
goes to the directorys and changes all the files name to the directory name.
The error :
Traceback (most recent call last):
File "D:\assets\steamcmd\yus.py", line 24, in <module>
os.rename(OurFilePath, os.path.join(pathy, pathname+str(file_extension)))
FileNotFoundError: [WinError 2] Nie można odnaleźć określonego pliku (cannot find file): 'steamapps\\workshop\\content\\573090\\2138774925\\.crash' -> 'steamapps\\workshop\\content\\573090\\2138774925\\2138774925
Code below which was used :
import os
directory = "steamapps\\workshop\\content\\573090\\"
for f in os.listdir(directory):
files = os.listdir()
pathy = os.path.join(directory, f)
for index,file in enumerate(files):
OurFilePath = os.path.join(pathy, file)
filename, file_extension = os.path.splitext(OurFilePath)
pathname = os.path.basename(pathy)
os.rename(OurFilePath, os.path.join(pathy, pathname+str(file_extension)))
Eventually, i found the error and have fixed the code.
The problem was : I used os.listdir the wrong way.
Heres the fixed code which i used :
directory = "steamapps\\workshop\\content\\573090\\"
for f in os.listdir(directory):
pathy = os.path.join(directory, f)
for file in os.listdir(pathy):
OurFilePath = os.path.join(pathy, file)
filename, file_extension = os.path.splitext(OurFilePath)
pathname = os.path.basename(pathy)
os.rename(os.path.join(os.path.join(directory, f), file), os.path.join(pathy, pathname+str(file_extension)))
I am trying to use the following code to unzip all the zip folders in my root folder; this code was found on this thread:
Unzip zip files in folders and subfolders with python
rootPath = u"//rootdir/myfolder" # CHOOSE ROOT FOLDER HERE
pattern = '*.zip'
for root, dirs, files in os.walk(rootPath):
for filename in fnmatch.filter(files, pattern):
print(os.path.join(root, filename))
zipfile.ZipFile(os.path.join(root, filename)).extractall(os.path.join(root, os.path.splitext(filename)[0]))
but I keep getting this error that says FileNotFoundError saying the xlsx file does not exist:
Traceback (most recent call last):
File "//rootdir/myfolder/Python code/unzip_helper.py", line 29, in <module>
zipfile.ZipFile(os.path.join(root, filename)).extractall(os.path.join(root, os.path.splitext(filename)[0]))
File "//rootdir/myfolder/Python\Python36-32\lib\zipfile.py", line 1491, in extractall
self.extract(zipinfo, path, pwd)
File "//myaccount/Local\Programs\Python\Python36-32\lib\zipfile.py", line 1479, in extract
return self._extract_member(member, path, pwd)
File "//myaccount/Local\Programs\Python\Python36-32\lib\zipfile.py", line 1542, in _extract_member
open(targetpath, "wb") as target:
FileNotFoundError: [Errno 2] No such file or directory: '\\rootdir\myfolder\._SGS Naked 3 01 WS Kappa Coated and a very long very long file name could this be a problem i dont think so.xlsx'
My question is, why would it want to unzip this excel file anyways?!
And how can I get rid of the error?
I've also tried using r instead of u for rootPath:
rootPath = r"//rootdir/myfolder"
and I get the same error.
Any help is truly appreciated!
Some filenames and directory names may have extra dots in their names, as a consequence the last line, unlike Windows filenames can have dots on Unix:
zipfile.ZipFile(os.path.join(root, filename)).extractall(os.path.join(root, os.path.splitext(filename)[0]))
this line fails. To see how that happens:
>>> filename = "my.arch.zip"
>>> root = "/my/path/to/mydir/"
>>> os.path.join(root, os.path.splitext(filename)[0])
'/my/path/to/mydir/my.arch'
With or without extra dots, problems will still take place in your code:
>>> os.path.join(root, os.path.splitext(filename)[0])
'/my/path.to/mydir/arch'
If no '/my/path.to/mydir/arch' can be found, FileNotFoundError will be raised. I suggest that you be explicit in you path, otherwise you have to ensure the existence of those directories.
ZipFile.extractall(path=None, members=None, pwd=None)
Extract all members from the archive to the current working directory. path specifies a different directory to extract to...
Unless path is an existent directory, FileNotFoundError will be raised.
import os
for filename in os.listdir("."):
if not filename.startswith("renamefilesindir"):
for filename2 in os.listdir(filename):
if filename2.startswith("abcdefghij"):
newName = "[abcdefghij.com][abcde fghij][" + filename + "][" + filename2[11:16] + "].jpg"
print(filename2)
print(newName)
os.rename(filename2, newName)
I have a folder with a few hundred other folders inside of it. Inside each secondary folder is a number of files all similarly named. What I want to do is rename each file, but I get the following error whenever I run the above program.
abcdefghij_88741-lg.jpg
[abcdefghij.com][abcde fghij][3750][88741].jpg
Traceback (most recent call last):
File "C:\directory\renamefilesindir.py", line 9, in <module>
os.rename(filename2, newName)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'abcdefghij_88741-lg.jpg' -> '[abcdefghij.com][abcde fghij][3750][88741].jpg'
I don't know what this means. It prints the existing file name, so I know it's found the file to be changed. Am I renaming the file wrong? What can't it find?
os.listdir contains just the names of the files and not the full paths. That's why your program actually tried to rename a file inside your current directory and it failed. So you could do the following:
import os.path
os.rename(os.path.join(filename, filename2), os.path.join(filename, newName))
since file with name filename2 is inside directory with name filename.
I have written a script to rename a file
import os
path = "C:\\Users\\A\\Downloads\\Documents\\"
for x in os.listdir(path):
if x.startswith('i'):
os.rename(x,"Information brochure")
When the python file is in a different directory than the path I get a file not found error
Traceback (most recent call last):
File "C:\Users\A\Desktop\script.py", line 5, in <module>
os.rename(x,"Information brochure")
FileNotFoundError: [WinError 2] The system cannot find the file specified:'ib.pdf'-> 'Information brochure'
But if I copy the python file to the path location it works fine
import os
for x in os.listdir('.'):
if x.startswith('i'):
os.rename(x,"Information brochure")
What is the problem?
Your variable x is currently only the filename relative to path. It's what os.listdir(path) outputs. As a result, you need to prepend path to x using os.path.join(path,x).
import os
path = "C:\\Users\\A\\Downloads\\Documents\\" #os.path.join for cross-platform-ness
for x in os.listdir(path):
if x.startswith('i'): # x, here is the filename. That's why it starts with i.
os.rename(os.path.join(path,x),os.path.join(path,"Information brochure"))
The x variable has the name of the file but not the full path to the file. Use this:
os.rename(path + "\\" + x, "Information brochure")
This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 9 years ago.
im having problems trying to run an iteration over many files in a folder, the files exist, if I print file from files I can see their names...
Im quite new to programming, could you please give me a hand? kind regards!
import os
for path, dirs, files in os.walk('FDF\FDF'):
for file in files:
print file
fdf = open(file, "r")
IOError: [Errno 2] No such file or directory: 'FDF_20110612_140613_...........txt'
You need to prefix each file name with path before you open the file.
See the documentation for os.walk.
import os
for path, dirs, files in os.walk('FDF\FDF'):
for file in files:
print file
filepath = os.path.join(path, file)
print filepath
fdf = open(filepath, "r")
Try this:
import os
for path, dirs, files in os.walk('FDF\FDF'):
for file in files:
print file
with open(os.path.join(path, file)) as fdf:
# code goes here.