import os
import shutil
os.chdir('C:\\')
dir_src = ('C:\\Users\\Tibi\\Desktop\\New Folder\\New Folder')
dir_dst = ('D:\\test')
for folder in os.walk(dir_src):
print(folder)
for filename in os.listdir(dir_src):
if filename.endswith('.CR2'):
shutil.copy(dir_src + filename, dir_dst)
print(filename)
Note that the file causing it to quit is one of the files I want to copy to the test folder. I tried using other file types and they don't work either.
output:
Traceback (most recent call last):
File "copyfiletree.py", line 14, in <module>
shutil.copy(dir_src + filename, dir_dst)
File "C:\Users\Tibi\Anaconda3\lib\shutil.py", line 235, in copy
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "C:\Users\Tibi\Anaconda3\lib\shutil.py", line 114, in copyfile
with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\New FolderIMG_5221.CR2'
I think I should mention that my computer is infected with Spora ransomware (however, these files are not encrypted).
NEW CODE I'M TRYING TO USE:
import os
import shutil
#os.chdir('C:\\')
dir_src = ('D:\\Users\\Tibi\\Pictures')
dir_dst = ('D:\\test')
#while True:
# try:
# for folder in os.walk(dir_src):
# print(folder)
# for filename in os.listdir(dir_src):
# if filename.endswith('.CR2'):
# shutil.copy(dir_src + '\\' + filename, dir_dst)
# print(filename)
# except UnicodeEncodeError:
# print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>File %s was Skipped!<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" %filename)
import pathlib
import glob
dir_src = pathlib.Path(r'D:\\Users\\Tibi\\Pictures//Move')
dir_dst = pathlib.Path(r'D:\test')
for file in dir_src.rglob('*.mp4'):
shutil.copy(str(file), str(dir_dst / file.name))
print("Current File is: %s" % file)
In general, don't make paths using +. Use os.path.join which is smarter:
shutil.copy(os.path.join(dir_src, filename), dir_dst)
This will give you C:\...\folder\file instead of C:\...\folderfile.
Alternatively, you can use pathlib:
import pathlib
import shutil
dir_src = pathlib.Path(r'C:\Users\Tibi\Desktop\New Folder\New Folder')
dir_dst = pathlib.Path(r'D:\test')
for file in dir_src.rglob('*.CR2'):
shutil.copy(str(file), str(dir_dst / file.name))
If you need to match regardless of case, use this '*.[Cc][Rr]2' instead of '*.CR2'.
Add a path separator between to prevent C:\\New FolderIMG_5221.CR2 nonexistant file. Change this:
dir_src + filename
to this:
dir_src + '\\' + filename
or this for a more generic solution that might not be on Windows:
dir_src + os.path.sep + filename
Related
I am trying to do my own sort of Files2Folder in python, as it would be a lot more automated for my needs. I have it so that it creates a folder from the filename, but anytime I try to move the file into the newly created folder, I am returned an error. Any ideas?
import os
import os.path
import shutil
from pathlib import Path
import glob
rootdir = r'T:\rcloneFolder'
keepExt = ('.mkv', '.mp4', '.avi')
searchPath = Path(rootdir)
for file in searchPath.rglob("*"):
if file.name.endswith(keepExt):
print(file)
newName = (os.path.splitext(file.name)[0])
newFolders = os.mkdir(os.path.join(searchPath,newName))
print("Made File Directory: " + newName)
name = newName + '.mkv'
shutil.move(file, os.path.join(rootdir, name))
I think what you are looking for is that you need to use rootdir instead of searchPath to os.path.join since join expects a plain string, then the new filename is going to be os.path.join(rootdir, newName, newName) + ".mkv" since you want to rename the extension and move it into the folder with the same name, so the following code I believe would do what you are looking for:
for file in searchPath.rglob("*"):
if file.name.endswith(keepExt):
print(file)
name = (os.path.splitext(file.name)[0])
newFolder = os.path.join(rootdir,name)
os.mkdir(newFolder)
print("Made File Directory: " + newFolder)
destination = os.path.join(newFolder, name) + '.mkv'
shutil.move(file, destination)
from pathlib import Path
import glob, os
import shutil
for file in glob.glob('*.webm'):
folder_name = file.split('.')[0]
Path(folder_name).mkdir(parents=True, exist_ok=True)
shutil.move(file, folder_name)
I am using python to rename files which exist as binary files but in actual are images. So I need to rename them into .jpg format. I am using os.rename() but getting the error:
Traceback (most recent call last):
File "addext.py", line 8, in <module>
os.rename(filename, filename + '.jpg')
OSError: [Errno 2] No such file or directory
Here's my code.
import os
for filename in os.listdir('/home/gpuuser/Aditya_Nigam/lum2/'):
# print(filename + '.jpg')
# k = str(filename)
# print k
# k = filename + '.jpg'
os.rename(filename, filename + '.jpg')
print('Done')
os.listdir only return a list of filenames without their absolute paths, and os.rename will attempt to lookup a filename from the current directory unless given an absolute path. Basically, the code as-is will only work when executed in the same directory as the one called by os.listdir.
Consider doing the following:
import os
from os.path import join
path = '/home/gpuuser/Aditya_Nigam/lum2/'
for filename in os.listdir(path):
os.rename(join(path, filename), join(path, filename) + '.jpg')
The os.path.join method will safely join the path with the filenames together in a platform agnostic manner.
I am trying to rename a file in a folder and i keep getting the error that the file is not there....
import os
import time
from os.path import isfile, join
working_dir = ('C:/Users/XXXXX/Desktop')
only_file = [f for f in os.listdir(working_dir) if os.path.isfile(os.path.join(working_dir, f))]
print only_file
time_srt = time.strftime("%d_%m_%Y")
if 'EZShift_WeeklyPerDayScheduleReport_Export.xlsx' in only_file:
os.rename('EZShift_WeeklyPerDayScheduleReport_Export.xlsx', "EZShift_" + time_srt + ".xlsx")
C:\Python27\python.exe
C:/Users/xxxxxx/Desktop/Paython/Python3/pbx.py
['xxxxxx.jpg', 'xxxx.zip', 'xxxx.xlsx', 'xxx.pdf', 'xxx.MOV', 'xx.MOV', 'xxxxx_18_12_2016.xlsx', 'EZShift_WeeklyPerDayScheduleReport_Export.xlsx','Test_EZShift_WeeklyPerDayScheduleReport_Export.xlsx']
Traceback (most recent call last):
File "C:/Users/sabaja/Desktop/Paython/Python3/pbx.py", line 24, in
os.rename('EZShift_WeeklyPerDayScheduleReport_Export.xlsx', "EZShift_" + time_srt + ".xlsx")
WindowsError: [Error 2] The system cannot find the file specified
Process finished with exit code 1
your filenames from os.listdir are relative paths (os.listdir returns the filenames onla); they will be searched for in your current working directory which is os.getcwd() (that will not be changed just because you name a variable working_dir)
you need to os.path.join(working_dir, filename) to get absolute paths in order to access (and rename) your files.
you could do something like this:
import os.path
if 'EZShift_WeeklyPerDayScheduleReport_Export.xlsx' in only_file:
old_path = os.path.join(working_dir, "EZShift_WeeklyPerDayScheduleReport_Export.xlsx")
new_path = os.path.join(working_dir, "EZShift_" + time_srt + ".xlsx")
os.rename(old_path, new_path)
I'm trying to rename a number of files stored within subdirectories by removing the last four characters in their basename. I normally use glob.glob() to locate and rename files in one directory using:
import glob, os
for file in glob.glob("C:/Users/username/Desktop/Original data/" + "*.*"):
pieces = list(os.path.splitext(file))
pieces[0] = pieces[0][:-4]
newFile = "".join(pieces)
os.rename(file,newFile)
But now I want to repeat the above in all subdirectories. I tried using os.walk():
import os
for subdir, dirs, files in os.walk("C:/Users/username/Desktop/Original data/"):
for file in files:
pieces = list(os.path.splitext(file))
pieces[0] = pieces[0][:-4]
newFile = "".join(pieces)
# print "Original filename: " + file, " || New filename: " + newFile
os.rename(file,newFile)
The print statement correctly prints the original and the new filenames that I am looking for but os.rename(file,newFile) returns the following error:
Traceback (most recent call last):
File "<input>", line 7, in <module>
WindowsError: [Error 2] The system cannot find the file specified
How could I resolve this?
You have to pass the full path of the file to os.rename. First item of the tuple returned by os.walk is the current path so just use os.path.join to combine it with file name:
import os
for path, dirs, files in os.walk("./data"):
for file in files:
pieces = list(os.path.splitext(file))
pieces[0] = pieces[0][:-4]
newFile = "".join(pieces)
os.rename(os.path.join(path, file), os.path.join(path, newFile))
I'm trying to rename all the pictures in a directory. I need to add a couple of pre-pending zero's to the filename. I'm new to Python and I have written the following script.
import os
path = "c:\\tmp"
dirList = os.listdir(path)
for fname in dirList:
fileName = os.path.splitext(fname)[0]
fileName = "00" + fname
os.rename(fname, fileName)
#print(fileName)
The commented print line was just to verify I was on the right track. When I run this I get the following error and I am at a loss how to resolve it.
Traceback (most recent call last): File
"C:\Python32\Code\add_zeros_to_std_imgs.py", line 15, in
os.rename(fname, fileName) WindowsError: [Error 2] The system cannot find the file specified
Any help is greatly appreciated. Thnx.
You should pass the absolute path to os.rename. Right now your only passing the filename itself. It isn't looking in the correct place. Use os.path.join.
Try this:
import os
path = "c:\\tmp"
dirList = os.listdir(path)
for fname in dirList:
fileName = os.path.splitext(fname)[0]
fileName = "00" + fname
os.rename(os.path.join(path, fname), os.path.join(path, fileName))
#print(fileName)