Error [183] when using python os.rename - python

This is my first time using python and I keep running into error 183. The script I created searches the network for all '.py' files and copies them to my backup drive. Please don't laugh at my script as this is my first.
Any clue to what I am doing wrong in the script?
import os
import shutil
import datetime
today = datetime.date.today()
rundate = today.strftime("%Y%m%d")
for root,dirr,filename in os.walk("p:\\"):
for files in filename:
if files.endswith(".py"):
sDir = os.path.join(root, files)
dDir = "B:\\Scripts\\20120124"
modname = rundate + '_' + files
shutil.copy(sDir, dDir)
os.rename(os.path.join(dDir, files), os.path.join(dDir, modname))
print "Renamed %s to %s in %s" % (files, modname, dDir)

I'm guessing you are running the script on windows. According to the list of windows error codes error 183 is ERROR_ALREADY_EXISTS
So I would guess the script is failing because you're attempting to rename a file over an existing file.
Perhaps you are running the script more than once per day? That would result in all the destination files already being there, so the rename is failing when the script is run additional times.
If you specifically want to overwrite the files, then you should probably delete them using os.unlink first.

Given the fact that error 183 is [Error 183] Cannot create a file when that file already exists, you're most likely finding 2 files with the same name in the os.walk() call and after the first one is renamed successfully, the second one will fail to be renamed to the same name so you'll get a file already exists error.
I suggest a try/except around the os.rename() call to treat this case (append a digit after the name or something).
[Yes, i know it's been 7 years since this question was asked but if I got here from a google search maybe others are reaching it too and this answer might help.]

I just encounter the same issue, when you trying to rename a folder with a folder that existed in the same directory has the same name, Python will raise an error.
If you trying to do that in Windows Explorer, it will ask you if you want to merge these two folders. however, Python doesn't have this feature.
Below is my codes to achieve the goal of rename a folder while a same name folder already exist, which is actually merging folders.
import os, shutil
DEST = 'D:/dest/'
SRC = 'D:/src/'
for filename in os.listdir(SRC): # move files from SRC to DEST folder.
try:
shutil.move(SRC + filename, DEST)
# In case the file you're trying to move already has a copy in DEST folder.
except shutil.Error: # shutil.Error: Destination path 'D:/DEST/xxxx.xxx' already exists
pass
# Now delete the SRC folder.
# To delete a folder, you have to empty its files first.
if os.path.exists(SRC):
for i in os.listdir(SRC):
os.remove(os.path.join(SRC, i))
# delete the empty folder
os.rmdir(SRC)

Related

shutil.move() creates duplicates and fails on subsequent calls

I finished writing a script which creates some files so I'm making a tidy() function which sorts these files in folders. The end result should look like this:
/Scripting
- Output
- script.py
/Scripting/Output
- Folder1
- Folder2
- Folder3
Each folder contains the necessary files
I managed to create the list of folders and get the files in them without any problem so I now have in /Project: script.py, folder1, folder2, etc... I copy pasted most of the code from the first part in order to move them into the Output folder. The following code is executed with every subfolder containing their respective files is located in the same directory as the script.
try:
os.mkdir('output')
except FileExistsError:
pass
for file in os.listdir():
if '.' not in file and file != 'output':
shutil.move(file, f'{os.getcwd()}/output/{file})
The problem is that if I look into my folder after running, I find the following directory tree:
/Output
- Folder1
- Folder1
- File1
- File2
I get a duplicate folder within that folder and I don't understand where it's coming from. If I try to call the script again, I get the error: shutil.Error destination path 'Scripting/output/folder1/fodler1' already exists
What am I doing wrong?
Edit:
Here's the new code:
try:
os.mkdir('output')
except FileExistsError:
pass
obj = os.scandir()
cwd = os.getcwd()
for entry in obj:
if entry.is_dir() and not entry.name.startswith('.'):
continue
shutil.move(entry.name, f'{cwd}/'/output/'{entry.name}')
This works the first time I run it, but breaks if I keep calling the script by giving me the same mistake as above. It creates folder1 within folder1 only on subsequent calls and I can't find a reason for it.
Found the answer mostly by trial and error. I initially chose to use shutil.move() because it replaces a file if it finds another one with the same name. However, it does not do this with directory. It will instead add to that path. /Scripting/Output/Folder1/ as a destination path for Folder1 would give an error when I run the script a second time so instead of replacing the folder, it simple adds it into its path which would then become /Scripting/Output/Folder1/Folder1/ while still adding the files to the initial path (it looks like it runs the shutil.move() on everything within that path). To fix this, use obj = os.scandir() with obj.is_dir() and obj.name to parse your folders. Either os.rmdir() the extra folder every time, or add the folders before adding the files. This is the code that worked for me:
cwd = os.getcwd()
try:
os.mkdir('output')
except:
pass
os.chdir('output')
for name in folder_names:
try:
os.mkdir(name)
except:
pass
os.chdir('..')
obj = os.scandir()
cwd = os.getcwd()
for f in obj:
if f.is_file():
if True:# depends on how your files are organized
shutil.move(f.name, f'{cwd}/output/folder1/{f.name}')
# Do this for every file

Python. Create folder if it does not exist. But more complicated [duplicate]

This question already has answers here:
Creating 100+ folders and naming them sequentially [closed]
(5 answers)
Closed 2 years ago.
I'm making a python program using the Flask framework, but I have a problem.
I'll explain.
I need to save some images in a directory. So I have to create a directory called Folder, but first I have to check if this directory doesn't already exist.
So I should check if Folder exists, if it doesn't exist I create Folder directory, otherwise I create Folder1 directory.
But in the same way I have to check if Folder1 exists and if it already exists I see for the Folder2 directory and so on ...
After creating the directory I need to always use the same directory to save all the images.
That is, even if I terminate the program, the next time I run it must always save the other images in the directory created.
I ask for your help in doing this, because I don't know how to do it.
I tried to do this, but it doesn't work as it should:
path = "path/to/folder"
def create_directory():
global path
if(os.path.isdir(path)==False):
os.makedirs(path)
else:
cont=1
new_path = path
while(os.path.isdir(new_path)==True):
new_path = str(path)+str(cont)
cont= cont +1
os.makedirs(new_path)
Hope this code helps:
import os
# define the name of the directory to be created
path = "/root/directory1"
try:
os.mkdir(path)
except OSError:
print ("Creation of the directory %s failed" % path)
else:
print ("Successfully created the directory %s " % path)
This can use a number of error handling (in case regex fails, etc) but should get you started on the correct path:
import regex
from pathlib import Path
def mkdir(path_str):
path = Path(path_str)
# this while loop ensures you get the next folder name (the correct number appended to the base folder name)
while path.exists():
s= re.search('(\w+)(\d+)',path.name)
base,number = s.groups()
new_path_str = base + str(int(number)+1)
path = path.parent.joinpath(new_path_str)
try:
path.mkdir()
print(f'The directory {path.name} was created!')
except OSError:
print (f"Creation of the directory {path} failed")

Python script that creates new file and returns list of files

I'm trying to create a python script called script.py with new_directory function that creates a new directory inside the current working directory, then creates a new empty file inside the new directory, and returns the list of files in that directory.
The output I get is ["script.py"] which looks correct but gives me this error:
RuntimeErrorElement(RuntimeError,Error on line 5:
directory = os.mkdir("/home/PythonPrograms")
FileExistsError: [Errno 17] File exists: '/home/PythonPrograms'
)
import os
def new_directory(directory, filename):
if os.path.isdir(directory) == False:
directory = os.mkdir("/home/PythonPrograms")
os.chdir("PythonPrograms")
with open("script.py", "w") as file:
pass
# Return the list of files in the new directory
return os.listdir("/home/PythonPrograms")
print(new_directory("PythonPrograms", "script.py"))
How do I correct and why is this wrong?
As others have said, it is hard to debug without the error. In the right cercumstances, your code will work without errors. As #Jack suggested, I suspect you're current directory is not /home. This means you've created a directory called PythonPrograms in /home directory. os.chdir("PythonPrograms") is trying to change the directory to <currentDirectory>/PythonPrograms, which doesn't exist.
I have tried to rework your code (without completely changing it), into something that should work in all cases. I think the lesson here is, work with the variables you already have (i.e. directory), rather than hardcoding it into the function.
import os
def new_directory(directory, filename):
if not os.path.isdir(directory):
# Create directory within current directory
# This is working off the relative path (from your current directory)
directory = os.mkdir(directory)
# Create file if does not exist
# this is a one-liner version of you with...pass statement
open(os.path.join(directory, filename), 'a').close()
# Return the list of files in the new directory
return os.listdir(directory)
print(new_directory("PythonPrograms", "script.py"))
I hope that helps.
I'm guessing the error you're getting is because you're not able to switch directories to PythonPrograms? This would be because your python current working directory does not contain it. If you more explicitly write out the directory you want to switch to, for example putting os.chdir("/home/PythonPrograms"), then it may work for you.
Ideally you should give us any stack traces or more info on the errors, though
I'm not sure why in your code you have with open("script.py", "w") as file: pass,
but here is mt way:
import os
os.mkdir('.\\Newfolder') # Create a new folder called Newfolder in the current directory
open('.\\Newfolder\\file.txt','w').close() # Create a new file called file.txt into Newfolder
print(os.listdir('.')) # Print out all the files in the current directory

Python - How to handle folder creation if folder already exists

def copy_excel():
srcpath = "C:\\Aloha" #where the excel files are located
srcfiles = os.listdir(srcpath) #sets srcfiles as list of file names in the source path folder
destpath = "C:\\" #destination where the folders will be created
destdir = list(set([filename[19:22] for filename in srcfiles])) #extract three digits from filename to use for folder creation (i.e 505, 508, 517,...)
#function to handle folder creation
def create(dirname, destpath):
full_path = os.path.join(destpath, dirname)
if os.path.exists(full_path):
pass
else:
os.mkdir(full_path)
return full_path
#function to handle moving files to appropriate folders
def move(filename, dirpath):
shutil.move(os.path.join(srcpath, filename), dirpath)
#creates the folders with three digits as folder name by calling the create function above
targets = [(folder, create(folder, destpath)) for folder in destdir]
#handles moving files to appropriate folders if the three digits in file name matches the created folder
for dirname, full_path in targets:
for filename in srcfiles:
if dirname == filename[19:22]:
move(filename, full_path)
else:
pass
I am somewhat new to Python so please bear with me! I was able to find this code block on this site and tailored it to my specific use case. The code works well for creating the specified folders and dropping the files into the corresponding folders. However, when I run the code again for new files that are dropped into the "C:\\Aloha" I get a Error 183: Cannot create a file when that file already exists. In this case, the folder already exists because it was previously created when the script was run the first time.
The code errors out when targets attempts to create folders that already exist. My question is, what is the logic to handle folders that already exists and to ignore the error and just move the files to the corresponding folders? The script should only create folders if they are not already there.
Any help would be greatly appreciated! I have attempted try/except and nesting if/else statements as well as os.path.isdir(path) to check to see if the directory exists but I haven't had any luck. I apologize for any of the comments that are wrong, I am still learning Python logic as I build this script out.
You could use os.makedirs which not only will create cascading directories such that for instance C:\foo\bar\qux will create foo, bar and qux in case they do not exist, but you can also set the exist_ok=True such that no error is thrown if the directory exists.
So:
os.makedirs(full_path,exist_ok=True)
In case you want to throw an error or stop the processing if the directory exists, you can use os.path.exists(full_path) before mkdir.
Another option I just came by...
try:
os.mkdir(path)
except FileExistsError:
pass

Python - Errno 13 Permission denied when trying to copy files

I am attempting to make a program in Python that copies the files on my flash drive (letter D:) to a folder on my hard drive but am getting a PermissionError: [Errno 13] Permission denied: 'D:'.
The problematic part of my code is as follows:
# Copy files to folder in current directory
def copy():
source = getsource()
if source != "failure":
copyfile(source, createfolder())
wait("Successfully backup up drive"
"\nPress 'Enter' to exit the program")
else:
wait("No USB drive was detected"
"\nPress 'Enter' to exit")
# Create a folder in current directory w/ date and time
def createfolder():
name = strftime("%a, %b %d, %Y, %H.%M.%S", gmtime())
dir_path = os.path.dirname(os.path.realpath(__file__))
new_folder = dir_path + "\\" + name
os.makedirs(new_folder)
return new_folder
Everything seems to run fine until the copyfile() function runs, where it returns the error.
I tried replacing getsource() with the destination of the file instead and it returned the same permission error except for the new_folder directory instead.
I have read several other posts but none of them seem to be relevant to my case. I have full admin permissions to both locations as well.
Any help would be greatly appreciated!
As I stated in my comment above, it seems as if you're trying to open the directory, D:, as if it was a file, and that's not going to work because it's not a file, it's a directory.
What you can do is use os.listdir() to list all of the files within your desired directory, and then use shutil.copy() to copy the files as you please.
Here is the documentation for each of those:
os.listdir() (You will be passing the full file path to this function)
shutil.copy() (You will be passing each file to this function)
Essentially you would store all of the files in the directory in a variable, such as all_the_files = os.listdir(/path/to/file), then loop through all_the_files by doing something like for each_file in all_the_files: and then use shutil.copy() to copy them as you please.
If you're looking to copy an entire directory and its contents, then shutil.copytree(source, destination) can be used.

Categories