Errno 13 Permission Denied - python

I have researched the similarly asked questions without prevail. I am trying to os.walk() a file tree copying a set of files to each directory. Individual files seem to copy ok (1st iteration atleast), but an error is thrown (IOError: [Errno 13] Permission denied: 'S:/NoahFolder\.images') while trying to copy a folder (.images) and its contents? I have full permissions to this folder (I believe).
What gives?
import os
import shutil
import glob
dir_src = r'S:/NoahFolder/.*'
dir_dst = r'E:/Easements/Lynn'
src_files = glob.glob(dir_src)
print src_files
for path,dirname,files in os.walk(dir_dst):
for item in src_files:
print path
print item
shutil.copy(item, path)

shutil.copy will only copy files, not directories. Consider using shutil.copytree instead, that's what it was designed for.

This implementation of copytree seemed to get it done! Thanks for the input # holdenweb
from distutils.dir_util import copy_tree
for path,dirname,files in os.walk(dir_dst):
for item in src_files:
try:
shutil.copy(item, path)
except:
print item
print path
copy_tree(dir_src, path)

Related

python how to skip symlinks when checking folders

I made a script with python that creates placeholders in all empty directories so that they wont get deleted.
The problem with that is: it detects symlinks which I do not want to happen.
and I am getting error like: PermissionError: [Errno 13] Permission denied: 'system/d/'
code:
#!/usr/bin/env python3
import os, glob
dirs = []
paths = ["system", "vendor"]
for path in paths:
dirs.append(glob.glob(path + '/**/', recursive=True))
for dir in dirs:
for dir1 in dir:
if len(os.listdir(dir1)) == 0:
open(dir1, '.PLACEHOLDER').close()
else: continue
How do i ignore symlinks
Use os.walk instead of glob, as in:
dirs.append(list(os.walk(path, followlinks=False)))
( Please note that according to the documentation, the default for followLinks is False - so you can omit this argument. )

Permission denied in copying textfiles

I want to move a file to another folder, but my permissions seems to be denied.
I have tried googling the problem, and although this is probably a pretty simple problem, I am not able to find solutions. I am the administrator on the system.
import os
import shutil
import re
textregex = re.compile(r'(.*).txt')
folder_files = os.listdir('D:\\progetti python\\renamedates.py\\dates')
for filename in folder_files:
txtfiles = textregex.findall(filename)
print('found some text files: ' + filename)
for file in txtfiles:
shutil.copy(f'{file}','D:\\progettipython\\renamedates.py\\newfolder')
I expect to copy my file (which is a textfile) without having my copy denied.
I can give you an example how to copy just .txt from folder a to folder b:
using glob to easy check for textfile ext.
import shutil
import glob
textfiles = glob.glob(r'C:\foldera\*.txt')
for filename in textfiles:
shutil.copy(f'{filename}',r'C:\folderb')

why does python say it cant find the path specified when it made the path?

I made this program yesterday because I am using py2exe, so what this program does is it zips up the folder created by py2exe and names it to app4export so I can send it to my friends. I also added in where if i already have a zip file called app4export then it deletes it before hand, it worked yesterday but now today I get the error
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\severna\\Desktop\\Non_Test_Python_Files\\app4export'
but python made this location so I dont get why it cant find it later?
import os
import zipfile
import shutil
def zip(src, dst):
zf = zipfile.ZipFile("%s.zip" % (dst), "w", zipfile.ZIP_DEFLATED)
abs_src = os.path.abspath(src)
for dirname, subdirs, files in os.walk(src):
for filename in files:
absname = os.path.abspath(os.path.join(dirname, filename))
arcname = absname[len(abs_src) + 1:]
print('zipping %s as %s' % (os.path.join(dirname, filename),
arcname))
zf.write(absname, arcname)
zf.close()
source=r"C:\Users\severna\Desktop\Non_Test_Python_Files\dist"
destination=r"C:\Users\severna\Desktop\Non_Test_Python_Files\app4export"
shutil.rmtree(str(destination))
try:
zip(str(source), str(destination))
shutil.rmtree(str(source))
except FileNotFoundError:
print("Source cannot be zipped as it does not exist!")
Your code creates the file C:\Users\severna\Desktop\Non_Test_Python_Files\app4export.zip, but you try to remove the directory C:\Users\severna\Desktop\Non_Test_Python_Files\app4export
So just before the try-block you have
shutil.rmtree(str(destination))
which will throw an FileNotFoundError if the path do not exist. And when you hit that line of code, you still havent created the path. The reason it might have worked yesterday was that you mayby had that path.
after discussion with Cleared I found out that I needed i file extension because it was a file and shutil.rmtree doesnt remove files it removes directories so I need to use this code instead
os.remove(str(destination)+".zip")

Renaming a single file in python

I'm trying to rename an audio file but I keep getting OSError: [Errno 2] No such file or directory.
In my program, each user has a directory that holds the users files. I obtain the path for each user by doing the following:
current_user_path = os.path.join(current_app.config['UPLOAD_FOLDER'], user.username)
/Users/johnsmith/Documents/pythonprojects/project/files/john
Now I want to obtain the path for the existing file I want to rename:
current_file_path = os.path.join(current_user_path,form.currentTitle.data)
/Users/johnsmith/Documents/pythonprojects/project/files/john/File1
The path for the rename file will be:
new_file_path = os.path.join(current_user_path, form.newTitle.data)
/Users/johnsmith/Documents/pythonprojects/project/files/john/One
Now I'm just running the rename command:
os.rename(current_file_path, new_file_path)
you can use os.rename for rename single file.
to avoid
OSError: [Errno 2] No such file or directory.
check if file exist or not.
here is the working example:
import os
src = "D:/test/Untitled003.wav"
dst = "D:/test/Audio001.wav"
if os.path.isfile(src):
os.rename(src, dst)
If the OS says there's no such file or directory, that's the gospel truth. You're making a lot of assumptions about where the file is, constructing a path to it, and renaming it. It's a safe bet there's no such file as the one named by current_file_path, or no directory to new_file_path.
Try os.stat(current_file_path), and similarly double-check the new file path with os.stat(os.posixpath.dirname(new_file_path)). Once you've got them right, os.rename will work if you've got permissions.
Try changing the current working directory to the one you want to work with. This code below should give you a simple walk through of how you should go about it:
import os
print (os.getcwd())
os.chdir(r"D:\Python\Example")
print (os.getcwd())
print ("start")
def rename_files():
file_list= os.listdir(r"D:\Python\Example")
print(file_list)
for file_name in file_list:
os.rename(file_name,file_name.translate(None,"0123456789")) rename_files()
print("stop")
print (os.getcwd())

Recovering filenames from a folder in linux using python

I am trying to use the listdir function from the os module in python to recover a list of filenames from a particular folder.
here's the code:
import os
def rename_file():
# extract filenames from a folder
#for each filename, rename filename
list_of_files = os.listdir("/home/admin-pc/Downloads/prank/prank")
print (list_of_files)
I am getting the following error:
OSError: [Errno 2] No such file or directory:
it seems to give no trouble in windows, where you start your directory structure from the c drive.
how do i modify the code to work in linux?
The code is correct. There should be some error with the path you provided.
You could open a terminal and enter into the folder first. In the terminal, just key in pwd, then you could get the correct path.
Hope that works.
You could modify your function to exclude that error with check of existence of file/directory:
import os
def rename_file():
# extract filenames from a folder
#for each filename, rename filename
path_to_file = "/home/admin-pc/Downloads/prank/prank"
if os.exists(path_to_file):
list_of_files = os.listdir(path_to_file)
print (list_of_files)

Categories

Resources