Python File Renaming Issue - python

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.

Related

finding a string given a directory, extension, and string?

Currently, I'm trying to determine how to return a list of filenames in the directory containing a particular string...
here's how i began:
def searchABatch(directory, extension, searchString):
for file in os.listdir(directory):
if fnmatch.fnmatch(file, extension):
return file
print(searchABatch("procedural", ".py", "foil"))
I expected it to print simply the files with the extension ".py" in my "procedural" directory but I am getting the following error:
Traceback (most recent call last):
File "pitcher20aLP2.py", line 38, in <module>
print(searchABatch("procedural", ".py", "foil"))
File "pitcher20aLP2.py", line 34, in searchABatch
for file in os.listdir(directory):
FileNotFoundError: [Errno 2] No such file or directory: 'procedural'
You're trying to print contents of directory that doesn't exist in you current working directory. You should check if provided directory is actually a directory before calling os.listdir(), by using os.path.isdir()
def searchABatch(directory, extension, searchString):
if os.path.isdir(directory):
for file in os.listdir(directory):
if fnmatch.fnmatch(file, extension):
return file
print(searchABatch("procedural", ".py", "foil"))
Kevin is right, you are trying to find procedural in /home/2020/pitcher20a/procedural directory.
Check your working directory with os.getcwd() and change it needed by using os.chdir(path). Also, you can check if the directory is even a directory by using os.path.isdir() before using os.listdir().
Here is the python os module documentation - https://docs.python.org/2/library/os.html
Also, try to handle the errors gracefully.

why zipfile trying to unzip xlsx files?

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.

Creating text file: IOError: [Errno 21] Is a directory: '/Users/muitprogram/PycharmProjects/untitled/HR/train.txt'

I am trying to write to create and write to a text file. However, the error
Traceback (most recent call last):
File "/Users/muitprogram/PycharmProjects/untitled/histogramSet.py", line 207, in <module>
drinktrainfile = open(abs_file_path, "w")
IOError: [Errno 21] Is a directory: '/Users/muitprogram/PycharmProjects/untitled/HR/train.txt'
shows up. There are other instances of this in Stack Overflow, however, none of these deal with creating and writing a new file. The directories all exist however- only the file is being created The code that does this is:
import os
script_path = os.path.abspath(__file__) # i.e. /path/to/dir/foobar.py
script_dir = os.path.split(script_path)[0] # i.e. /path/to/dir/
rel_path = str(j) + "/train.txt" # HR/train.txt
abs_file_path = os.path.join(script_dir, rel_path) #/path/to/dir/HR/train.txt
drinktrainfile = open(abs_file_path, "w")
EDIT: train.txt shows up, except as a directory. How do I make it a text file?
The resource is actually a directory. It was very likely a mistake, as it is not likely that somebody would have created a directory by that name. First, remove that directory, and then try to create and open the file.
You can open the file with open('/Users/muitprogram/PycharmProjects/untitled/HR/train.txt', 'w'), assuming that the file does not already exist.

Python IOError: [Errno 2] from recursive directory call

The code below is part of a program I am writing that runs a method on every .py, .sh. or .pl file in a directory and its folders.
for root, subs, files in os.walk("."):
for a in files:
if a.endswith('.py') or a.endswith('.sh') or a.endswith('.pl'):
scriptFile = open(a, 'r')
writer(writeFile, scriptFile)
scriptFile.close()
else:
continue
When writing the program, it worked in the directory tree I wrote it in, but when I moved it to another folder to try it there I get this error message:
Traceback (most recent call last):
File "versionTEST.py", line 75, in <module>
scriptFile = open(a, 'r')
IOError: [Errno 2] No such file or directory: 'enabledLogSources.sh'
I know something weird is going on because the file is most definitely there...
You'll need to prepend the root directory to your filename
scriptFile = open(root + '/' + a, 'r')
files contains only the file names, not the entire path. The path to the file can be obtained by joining the file name and the root:
scriptFile = open(os.path.join(root, a), "r")
You might want to have a look at
https://docs.python.org/2/library/os.html#os.walk

Path error in python

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")

Categories