Permission denied in copying textfiles - python

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

Related

Copy files with same extensions in the same directory to another directory - Python

I have some files in the same directory which have the same extension(.html). Those files need to all be copied to another directory. I've looked up documentations on both shutil and os but couldn't find any proper answer...
I have some pseudo codes as below:
import os, shutil
copy file1, file2, file3 in C:\abc
to C:\def
If anyone knows how to solve this, pls let me know. Appreciated!!
Some time ago I created this script for sorting files in a folder. try it.
import glob
import os
#get list of file
orig = glob.glob("G:\\RECOVER\\*")
dest = "G:\\RECOVER_SORTED\\"
count = 0
#recursive function through all the nested folders
def smista(orig,dest):
for f in orig:
#split filename at the last point and take the extension
if f.rfind('.') == -1:
#in this case the file is a folder
smista(glob.glob(f+"\\*"),dest)
else:
#get extension
ext = f[f.rfind('.')+1:]
#if the folder does not exist create it
if not os.path.isdir(dest+ext):
os.makedirs(dest+ext)
global count
os.rename(f,dest+ext+"\\"+str(count)+"."+ext)
count = count+1
#if the destination path does not exist create it
if not os.path.isdir(dest):
os.makedirs(dest)
smista(orig,dest)
input("press close to exit")
[assuming python3, but should be similiar in 2.7]
you can use listdir from os and copy from shutil:
import os, shutil, os.path
for f in listdir("/path/to/source/dir"):
if os.path.splitext(f)[1] == "html":
shutil.copy(f, "/path/to/target/dir")
warning: this is scrapped together without testing. corrections welcome
edit (cause i can't comment):
#ryan9025 splitext is fromos.path, my bad.
I finally got an correct answer by myself with a combinations of all the replies.
So if I have a python script in (a) directory, all the source files in (b) directory, and the destination is in (c) directory.
Below is the correct code that should work, and it looks very neat as well.
import os
import shutil
import glob
src = r"C:/abc"
dest = r"C:/def"
os.chdir(src)
for files in glob.glob("*.html"):
shutil.copy(files, dest)

Move Files that ends with .pdf to selected folder (Python)

My script I run will be on my mac.
My root is '/Users/johnle/Desktop/'
The purpose of the code is to move a tons of files.
On my desktop will be tons of .pdf files. I want to move the pdf files to '/Users/johnle/Desktop/PDF'
So : '/Users/johnle/Desktop/file.pdf' - > '/Users/johnle/Desktop/PDF/'
This is my code in python :
def moveFile(root,number_of_files, to):
list_of_file = os.listdir(root)
list_of_file.sort()
for file in list_of_file:
name = root + str(file)
dest = to + str(file)
shutil.move( name, dest )
You can use glob and shutil modules. For example:
import glob
import shutil
for f in glob.glob('/Users/johnle/Desktop/*.pdf'):
shutil.copy(f, '/Users/johnle/Desktop/PDF')
(this code hasn't been tested).
Note: my code copies files. If you want to move them, then replace shutil.copy with shutil.move.
In case you have .pdf files with inconsistent casing on their extensions (e.g. .PDF, .pdf, .PdF, ...), you can use something like this:
import os
import shutil
SOURCE_DIR = '/Users/johnle/Desktop/'
DEST_DIR = '/Users/johnle/Desktop/PDF/'
for fname in os.listdir(SOURCE_DIR):
if fname.lower().endswith('.pdf'):
shutil.move(os.path.join(SOURCE_DIR, fname), DEST_DIR)
The os module has lots of fun toys like this for manipulating files and other OS related operations.
You can use the rename function within the os module, to move the file to a new location.
import os
os.mkdir(<path>) #creates a new folder at the specified path
os.rename(<original/current path>, <new path>)

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)

Errno 13 Permission Denied

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)

Open existing file of unknown extension

I need to open a file for reading, I know the folder it is in, I know it exists and I know the (unique) name of it but I don't know the extension before hand.
How can I open the file for reading?
Use glob to find it:
import os
import glob
filename = glob.glob(os.path.join(folder, name + '.*'))[0]
Or with a generator:
filename = next(glob.iglob(os.path.join(folder, name + '.*')))

Categories

Resources