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.
Related
I want to open a folder containing x zipfiles.
I have this code:
parser = argparse.ArgumentParser(description='Test')
parser.add_argument("foldername", help="Foldername of log files archive to parse")
args = parser.parse_args()
with open(args.foldername) as files:
filename = args.filename
print(filename)
But I get error code:
PermissionError: [Errno 13] Permission denied: 'Test'
I would like the zipfiles in the folder to be listed in an array when I run the code.
I'm not sure why you're getting a permission error, but using open on a directory won't do what you want. The documentation for Python's open requires that its input is a string to a file, not a directory.
If you want the files in a directory given the name of the directory as a string, refer to How can I iterate over files in a given directory?
Are you sure you have permission to read those files? Test, whatever file or folder it is, doesn't seem to be readable from your script.
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
I have worked through a number of other threads on this, but not of their solutions seem to work here, that or I am not understanding properly, and would love your help.
I am getting a:
IOError: [Errno 13] Permission denied: 'W:\\test\\Temporary Folder 195\\Sub-fold1
This is the general code i started with.
summary_file = r'W:/test/SDC Analysis Summary.docm'
shutil.copyfile(summary_file, os.getcwd())
I have also varied this a little bit based on other threads, specifically replacing summary_file with the actual text and also adding \ to the end of working directory without success. Really don't know what I'm missing here. I know that the Documentation is looking for complete paths, but I believe I am satisfying that requirement. What am I missing here?
Note: there is a desire to use copyfile over copy due to the speed increase.
From the documentation:
dst must be the complete target file name
You can't just use os.getcwd() as the destination.
you should be the complete target file name for destination
destination = pathdirectory + filename.*
I use this code fir copy wav file with shutil :
# open file with QFileDialog
browse_file = QFileDialog.getOpenFileName(None, 'Open file', 'c:', "wav files (*.wav)")
# get file name
base = os.path.basename(browse_file[0])
os.path.splitext(base)
print(os.path.splitext(base)[1])
# make destination path with file name
destination= "test/" + os.path.splitext(base)[0] + os.path.splitext(base)[1]
shutil.copyfile(browse_file[0], destination)
I'm trying to use the shutil module to copy files from one drive to another. Since this is an ArcGIS script, I store the user's choice for folder source and destination locations as:
src = arcpy.GetParameterAsText(0)
dst = arcpy.GetParameterAsText(1)
Using arcpy.AddMessage(src) to print that out gives me:
C:\Folder1\Folder2\File.extension
Which is what I want! However, when I try to use shutil.copy(src,dst), I get:
u'C:\\Folder1\\Folder2\\File.extension'
IOError: [Errno 2] No such file or directory: u'C:\\Folder1\\Folder2'
What is happening here? Since I'm not spelling out the path I can't change the "u" to an "r" for raw input...
Shutil.copy/unicode wasn't the problem here; tyring to copy a non-existent file was.
As a form of file management validation, you should always check to see whether or not the directory exists. You can do this using the os.path.exists(path) method. If your path exists, you should have no problem. If not, then create it before copying your files over.
See example code below:
if not os.path.exists(dst):
os.mkdir(dst)
shutil.copy(src, dst)
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)