How to copy a folder (divide into sub folders) using Python? - python

i try to copy a directory (divided into folders and subfolders) to a new folder that will be created.i work with python 2.7.
dir_src = an exist folder
dir_dst = a new folder (not exist) that all the folders will be copied to
I read https://docs.python.org/2/library/shutil.html and tried this code:
import os,shutil
dir_src = r"C:\Project\layers"
dir_dst = r"C:\Project\new"
for file in os.listdir(dir_src):
print file
src_file = os.path.join(dir_src, file)
dst_file = os.path.join(dir_dst, file)
shutil.copytree(src_file, dst_file,symlinks=False, ignore=None)
print 'copytree'
But i get an error:
WindowsError: [Error 267] : 'C:\\Project\\layers\\abc.cpg/*.*'
Thank you very much for any help.

The error you are getting (Permission denied) should tell you what is the problem - you don't have rights to read or copy the files. Running the program as administrator should fix it.

About edited question and error:
WindowsError: [Error 267] : 'C:\\Project\\layers\\abc.cpg/*.*'
Please carefully read docs
import shutil
dir_src = r"C:\Project\layers"
dir_dst = r"C:\Project\new"
shutil.copytree(dir_src, dir_dst)
you not need any for.
Note:
Please keep in mind, that destination path shouldn't be existed.

Related

No such file or directory

I have faced error I had worked with this code before but now:
error
FileNotFoundError: [Errno 2] No such file or directory: 'pattern2_list.txt'
I use Python 3.8
import os
import shutil
with open ("pattern2_list.txt") as pattern_list_file:
pattern_data = pattern_list_file.read ()
pattern_list = pattern_data.split('\n')[:-1]
file_name_list = [file_name for file_name in os.listdir('2020')]
for file_name in file_name_list:
for pattern in pattern_list:
if pattern in file_name:
shutil.move("2020/" + file_name, "new_dir/"+ file_name)
Make sure that the file pattern2_list.txt
is present in the same working directory.
If you are in same directory and still it is not working then open a new folder and inside it create your python file with.pyextension.Inside same folder paste the pattern2_list.txtfile and then try to use it.
If still facing issue then check your python path in environment variable and if possible restart your system then open vs code.
Hope it will help you..

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

os.chdir() giving error with parsing the path

I am getting error while trying to change the Current directory to a different folder in python. My code is as below:
I take PATH_DIR as input from user and the user passes absolute path.
files[]
for directories in os.listdir(PATH_DIR):
files.append(directories)
for dir in files:
abs = os.path.abspath(dir)
print abs
os.chdir(abs)
In my compilation trail I give the PATH_DIR as C:\Python27\Scripts and the directories in this folder are 'WIN7' 'WIN8'. When I execute the program, I get an error as below.
WindowsError: [Error 2] The system cannot find the file specified: 'C:\Python27\Scripts\WIN7'
In principle, the command os.chdir() is some how adding a '\' character before every '\' in the directory path. Can you please help me solve this issue.
os.chdir(abs)
You are trying to cd into FILE.
os.listdir() will return full content of given directory.
You need to check whether entity is a directory with os.path.isdir()
import os
PATH_DIR = '.'
files = []
for directory in os.listdir(PATH_DIR):
print os.path.isdir(os.path.join('.', directory))
if os.path.isdir(os.path.join('.', directory)):
files.append(directory)
print files
for directory in files:
abs_path = os.path.abspath(directory)
print abs_path
os.chdir(abs_path)

Python:writing files in a folder to zipfile and compressing it

I am trying to zip and compress all the files in a folder using python. The eventual goal is to make this occur in windows task scheduler.
import os
import zipfile
src = ("C:\Users\Blah\Desktop\Test")
os.chdir=(src)
path = (r"C:\Users\Blah\Desktop\Test")
dirs = os.listdir(path)
zf = zipfile.ZipFile("myzipfile.zip", "w", zipfile.ZIP_DEFLATED,allowZip64=True)
for file in dirs:
zf.write(file)
Now when I run this script I get the error:
WindowsError: [Error 2] The system cannot find the file specified: 'test1.bak'
I know it's there since it found the name of the file it can't find.
I'm wondering why it is not zipping and why this error is occurring.
There are large .bak files so they could run above 4GB, which is why I'm allowing 64 bit.
Edit: Success thanks everyone for answering my question here is my final code that works, hope this helps my future googlers:
import os
import zipfile
path = (r"C:\Users\vikram.medhekar\Desktop\Launch")
os.chdir(path)
dirs = os.listdir(path)
zf = zipfile.ZipFile("myzipfile.zip", "w", zipfile.ZIP_DEFLATED,allowZip64=True)
for file in dirs:
zf.write(os.path.join(file))
zf.close()
os.listdir(path) returns names relative to path - you need to use zf.write(os.path.join(path, file)) to tell it the full location of the file.
As I said twice in my comments:
Python is not looking for the file in the folder that it's in, but in the current working directory. Instead of
zf.write(file)
you'll need to
zf.write(path + os.pathsep + file)

How to correctly move Files with Python

I already read some useful infos here about moving files with Python. But those are not working on my machine. I use eclipse to run python and the program should move files within windows.
I used os.rename, shutil.move, shutil.copy and so on....
Here is my simple code.
import os
import shutil
source = os.listdir("C:/test/")
dest_dkfrontend = "C:/test1/"
for files in source:
if files.startswith("Detail"):
print('Files found ' + files)
shutil.copy(files, dest_dkfrontend)
else:
print('File name not matching')
I receive an error like:
with open(src, 'rb') as fsrc:
IOError: [Errno 2] No such file or directory:
Could you please help to address this?
first you have to check if your destination directory exists or not.
and shutil.copy requires 1st parameter as source of file with file name and 2nd parameter as destination of file where to copy with new file name.
try this.
import os
import shutil
source = os.listdir("C:/test/")
dest_dkfrontend = "C:/test1/"
if not os.path.exists(dest_dkfrontend):
os.makedirs(dest_dkfrontend)
for files in source:
if files.startswith("Detail"):
print('Files found ' + files)
shutil.copy(source+files, dest_dkfrontend+files)
else:
print('File name not matching')

Categories

Resources