I am trying to copy specific files from one folder to another but I get an error I don't understand why :
import os
import shutil
def setPath_getData():
# Set up folders for data
newpath = r'userdata'
if not os.path.exists(newpath):
os.makedirs(newpath)
os.makedirs('userdata/sleep')
os.makedirs(r'userdata/distance')
os.makedirs(r'userdata/steps')
os.makedirs(r'userdata/lightly')
os.makedirs(r'userdata/mod')
os.makedirs(r'userdata/sedentary')
os.makedirs(r'userdata/very')
os.makedirs(r'userdata/heart-rate-zone')
os.makedirs(r'userdata/heart-rate')
# Get data from fitbit
filenames = os.listdir("user-site-export")
unique_filenames = set()
for f in filenames:
unique_filenames.add(f.split("-")[0])
source = os.listdir('user-site-export/')
dest = '/userdata/sleep/'
for file in source:
if file.startswith('sleep'):
shutil.copy(file, dest)
#ls userdata/
print("Data loaded successfully")
setPath_getData()
the error it gives is :
FileNotFoundError: [Errno 2] No such file or directory: 'sleep-2020-01-09.json'
So it looks like it is fetching the correct files but it does not copy them to dest. Any ideas why ?
You must specify the source path before the file variable in the copy command:
shutil.copy(os.path.join("user-site-export", file), dest)
Related
I have been trying to make a python file that will copy contents from one folder to another. I would like it to work on any Windows system that I run it on. It must copy ALL things ...
i need solution to this problem.
import shutil
import os
# Path to the directory
source = 'C:/path/to/source/folder'
# Path to the destination directory
destination = 'C:/path/to/destination/folder'
# Copy contents from source to destination
shutil.copytree(source, destination)
# List all the files in source directory
source_files = os.listdir(source)
# Iterate over all the files in source directory
for file_name in source_files:
# Create full path of file in source directory
full_file_name = os.path.join(source, file_name)
# If file is a directory, create corresponding directory in destination
# directory
if os.path.isdir(full_file_name):
shutil.copytree(full_file_name, os.path.join(destination, file_name))
else:
# Copy the file from source to destination
shutil.copy2(full_file_name, destination)
import shutil
import os
source = 'C:/path/to/source/folder'
destination = 'C:/path/to/destination/folder'
shutil.copytree(source, destination)
source_files = os.listdir(source)
for file_name in source_files:
full_file_name = os.path.join(source, file_name)
if os.path.isdir(full_file_name):
shutil.copytree(full_file_name, os.path.join(destination, file_name))
else:
shutil.copy2(full_file_name, destination)
This code should extract pictures from a xlsx file and save a copy and rename it three times in a new directory.
os.mkdir creates the directory on the desktop and saves the first picture but after that I get
os.rename(filename, new_name)
FileNotFoundError: [WinError 2] Impossible to find the specified file: 'image1.jpeg' -> 'newPicone0.jpeg
When I check the absolute path of the directory I got this
os.path.abspath('renamedPix')
'C:\\Users\\divel\\Desktop\\XLSpix\\renamedPix'
even though the directory is not in the XLSpix folder but on the desktop.
Checking for the directory's existence I get this:
os.path.exists('renamedPix')
False
I don't understand what is causing the problem.
Here is the complete code:
from zipfile import ZipFile
import re
import os
import shutil
file_name= "fote.xlsx"
directory= "renamedPix"
parent_dir = "C:\\Users\\divel\\Desktop"
path = os.path.join(parent_dir, directory)
os.mkdir(path)
with ZipFile(file_name, 'r') as zipObj:
counter = 0
for file in zipObj.infolist():
name = file.filename
match = re.findall("jpeg$", name)
if match:
filename = os.path.basename(file.filename)
for i in range(3):
source = zipObj.open(file)
target = open(os.path.join(path, filename), 'wb')
with source, target :
shutil.copyfileobj(source, target)
pic_names = ['one', 'two', 'three']
new_name = 'newPic'+pic_names[i]+str(counter)+'.jpeg'
os.rename(filename, new_name)
counter += 1
Thank you for your help.
Turning my comment into an answer: The problem was that the arguments to os.rename() were only file names, not path names. Thus the OS attempted to rename the files in the current working directory (where they did not exist). Passing the full path names to rename fixes the issue:
os.rename(os.path.join(path, filename), os.path.join(path, newname))
Im trying to run my code with this but keep running into a file not found error.
files = [i for i in os.listdir('C:/Users/me/Desktop/python data')]
for filename in files:
data = pandas.read_excel(str(filename))
I've tried looking around but cant seem to understand.
Running print(os.getcwd()) does find the file in the folder but i still get the error message
You need to concatenate the path and the filename returned from os.listdir:
PATH = 'C:/Users/me/Desktop/python data'
files = [os.path.join(PATH, i) for i in os.listdir(PATH)]
for filename in files:
data = pandas.read_excel(str(filename))
Further recommendations:
You can use pathlib's .glob to get the full path without using os.path.join.
Also, if you use read_excel, please consider filtering by xls/xlsx files:
Code example:
import pathlib
path = pathlib.Path('C:/Users/me/Desktop/python data')
excel_filter = "*.xls*"
for filename in path.glob(excel_filter):
print(filename)
I'm attempting to write a script that will save a file in the given directory, but I'm getting a NotADirecotryError[WinError 267] whenever I run it. Any ideas or tips on what I may have done incorrectly?
import shutil
import os
src = 'C:\\Users\\SpecificUsername\\Pictures\\test.txt\'
dest = 'C:\\Users\\SpecificUsername\\Desktop'
files = os.listdir(src)
for file in files:
shutil.copy(file, dest)
for file in files:
if os.path.isfile(file):
shutil.copy(file,dest) ```
There are a couple of things going on here:
You can just use forward slashes in the paths.
Your src is the test.txt file, and not a directory, so you cannot iterate over it using os.listdir().
You can also merge the two loops together since they are looping over the same set of data.
shutil.copy() takes a file path as input, while what you are passing is a filename.
The following code should work and it also copies directories as is:
import shutil
import os
basepath = "C:/Users/SpecificUsername/"
src = "Pictures/"
dest = "Desktop/"
files = os.listdir(os.path.join(basepath, src))
for filename in files:
filepath = os.path.join(basepath, src, filename)
if (os.path.isfile(filepath)):
print("File: " + filename)
shutil.copy(filepath,dest)
else:
print("Dir: " + filename)
shutil.copytree(filepath, os.path.join(dest, filename))
Hope it helps!
I have the following code (file path details kept anonymous):
def stu_activities():
downloadsList = os.listdir("***/Downloads")
destination = "."
for file_name in downloadsList:
if file_name.startswith("Stu_"):
shutil.copyfile(file_name,destination)
stu_activities()
When I run it, it gives me this error:
FileNotFoundError: [Errno 2] No such file or directory: 'Stu_activity.pptx'
How is it that it claims the file is not found yet it still found it?
I assume that your real code does not contain "***/Downloads" but a real path.
os.listdir() returns the filename, but not the full path to the filename.
shutil.copyfile() on the other hand needs the full path of the file.
Further the destination of shutil.copyfile() must be a file name and not a directory
def stu_activities():
dir_to_List = "/your/path/Downloads"
downloadsList = os.listdir(dir_to_list)
destination = "."
for file_name in downloadsList:
if file_name.startswith("Stu_"):
shutil.copyfile(
os.path.join(dir_to_list, file_name) ,
os.path.join(destination, file_name))
stu_activities()