Python Loop to move files - python

Once again, I am looking for some assiatance, thanks in advance. This code has the purpouse to move files in a list, from one folder to another.
It is giving me the ERROR below.
import shutil
Import os
source='/dev/sdc /mnt/mnttensor/Dhole/'
destination='/home/ubuntu/classificator/nodhole/'
fo = open("dhole3.txt", "r")
content = fo.readlines()
for files in content:
shutil.move(source+files,destination+files)
ERROR
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/usr/lib/python2.7/shutil.py", line 302, in move
copy2(src, real_dst)
File "/usr/lib/python2.7/shutil.py", line 130, in copy2
copyfile(src, dst)
File "/usr/lib/python2.7/shutil.py", line 82, in copyfile
with open(src, 'rb') as fsrc:
IOError: [Errno 2] No such file or directory: '/dev/sdc /mnt/mnttensor/Dhole/227_5267_M0423_19Oct12-IMAG0068.JPG\r\n'
I would really appreciate any help on this.

Look at the erroneous directory:
/dev/sdc /mnt/mnttensor/Dhole/227_5267_M0423_19Oct12-IMAG0068.JPG\r\n
Notice the \r\n at the end of the file. This is what most likely has caused the error, and this should be fixed by using a rstrip() method inside of the for-loop so it truncates the special characters when the shutil.move() method tries to find the files. So the for loop should look something like this:
for files in content:
shutil.move(source + files.rstrip("\r\n"), destination + files.rstrip("\r\n"))
Also notice the whitespace character at the /dev/sdc directory – that is likely unintentional and should probably be removed.

Related

How to move a file from one directory to another?

I am trying to make a script that gets all the pictures of my Images folder that have the jpg extension and moves them in the newimages folder.
Here is my code:
import os
import shutil
for filename in os.listdir("D:/Images/"):
if filename.endswith(".jpg"):
shutil.move(filename, r'D:/newimages/')
However when I run the code, I get the following error:
Traceback (most recent call last):
File "d:\Online_courses\Coursera\Google_IT_Automation\Automating_real-world_tasks_with_python\project1\script1.py", line 9, in <module>
shutil.move(filename, r'D:/newimages/')
File "C:\Users\Nicholas\AppData\Local\Programs\Python\Python37\lib\shutil.py", line 580, in move
copy_function(src, real_dst)
File "C:\Users\Nicholas\AppData\Local\Programs\Python\Python37\lib\shutil.py", line 266, in copy2
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "C:\Users\Nicholas\AppData\Local\Programs\Python\Python37\lib\shutil.py", line 120, in copyfile
with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: '20180331_164750.jpg'
when you use a filename it will just take a name. For copying you need a full path. Please try the same but with
for filename in os.listdir("D:/Images/"):
if filename.endswith(".jpg"):
shutil.move(os.path.join("D:/Images/", filename), os.path.join("D:/NewImages/", filename))
You need to append 'D:/Images/' to each filename. You're not in the D:/Images/ directory so Python isn't able to find those files.
old_dir = 'D:/Images'
new_dir = 'D:/newimages'
for filename in os.listdir(old_dir):
if filename.endswith(".jpg"):
shutil.move(f'{old_dir}/{filename}', new_dir)

How do I make my program move files without the .py file being in the source location

I wrote this program to move videos from my download folder to different destination folders.
import os
import shutil
import sys
folder = []
highlight = ['highlights','goals','skills']
comedy_word = ['comedy', 'acapella','seyilaw','basketmouth','basket mouth','bovi','gordons','buchi','rhythm unplugged','elenu','seyi law','akpororo','emmaohmygod','klint','shakara','funnybone','igodye','i go die','i go dye','igodye','whalemouth','whale mouth','daniel']
series_word = ['lost', 'thrones', 'vampire', 'originals', 'ship', '']
grub_word = ['programming', 'python', 'linux','exploit','hack']
for i in os.listdir('C:\\Users\\Afro\\Downloads\\Video'):
folder.append(i.lower())
def tv_series(series):
for serie in series:
if 'ship' in serie:
shutil.move(serie, 'C:\\Users\\Afro\\Desktop\\Movies\\Series\\The Last Ship\\The Last Ship 3\\' )
print(serie[:-3] +': Moved!')
elif 'lost' in serie:
shutil.move(serie, 'C:\\Users\\Afro\\Desktop\\Movies\\Series\\Lost\\s2\\' )
print(serie[:-3] +': Moved!')
The file's name is arrange.py and the program throws a filenotfound error when arrange.py is not in the "C:\Users\Afro\Downloads\Video" folder. Is it possible to make the program run in any folder?
Thanks
Here's the error it throws.
Traceback (most recent call last):
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 538, in move
os.rename(src, real_dst)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'lost - s02e08 (o2tvseries.com).mp4' -> 'C:\\Users\\Afro\\Desktop\\Movies\\Series\\Lost\\s2\\lost - s02e08 (o2tvseries.com).mp4'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Afro\Desktop\Arrange.py", line 77, in <module>
start(folder)
File "C:\Users\Afro\Desktop\Arrange.py", line 65, in start
tv_series(folder)
File "C:\Users\Afro\Desktop\Arrange.py", line 22, in tv_series
shutil.move(serie, 'C:\\Users\\Afro\\Desktop\\Movies\\Series\\Lost\\s2\\' )
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 552, in move
copy_function(src, real_dst)
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 251, in copy2
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 114, in copyfile
with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'lost - s02e08 (o2tvseries.com).mp4'
You call shutil.move specifying the reference point incorrectly. In your loop that gathers the files, you should use os.path.join('C:\\Users\\Afro\\Downloads\\Video', i) and put that in your list instead. Otherwise it's all relative paths, hence the FileNotFound error.
You could also change the working directory. This would make the script behave as if it was in a different folder. This can have some unintended consequences, so be careful. Details here.
Hope this helps!

combine 2 directories with it subdirectories

i have a problem with combining 2 folder with it subdirectories, i have 2 folder source. i named it : test-2 and test-2 and path to these folder is output/test-2 and output/test-4
i combined it with this line:
merged_folder_path = 'merged/dir/output'
shutil.copy(result_1_path, merged_folder_path)
shutil.copy(result_2_path, merged_folder_path)
but it get error:
Traceback (most recent call last):
File "jamu.py", line 769, in <module>
main(sys.argv)
File "jamu.py", line 757, in main
shutil.copy(result_1_path, merged_folder_path)
File "C:\Python27\lib\shutil.py", line 119, in copy
copyfile(src, dst)
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(src, 'rb') as fsrc:
IOError: [Errno 13] Permission denied: 'output/test-2'
is something wrong with my code?
i get the same problem here.
and it's working to me,
thanks for all the answers. apreciated it!
Check perms before copy/move/delete
import os
if os.access(merged_folder_path,os.W_OK):
shutil.copy(...,...)
os.F_OK: path is exists
os.R_OK: readability of path.
os.W_OK: writability of path.
os.X_OK path can be executed.

Shutil.move - First run Error, second run success

I looked for similar issues in this forum, but not came up with my situation.
I program python with Eclipse. I am using shutil.move to move some files from one directory to another. When I run the code first, it is giving me the following error. Right after this I run a second try (without changing anything), it finds me the correct files and move to the correct place. Does anyone know what I am doing wrong? If my code is faulty, why it is running in second try without any problem? The source and destination directories are already existing.
Here is the IOError:
Traceback (most recent call last):
File "C:\Users\john\workspace\RC\src\Test.py", line 82, in <module>
shutil.move('C:/RCTemp/' + filename, dest_sonst)
File "C:\Python27\Lib\shutil.py", line 302, in move
copy2(src, real_dst)
File "C:\Python27\Lib\shutil.py", line 130, in copy2
copyfile(src, dst)
File "C:\Python27\Lib\shutil.py", line 82, in copyfile
with open(src, 'rb') as fsrc:
IOError: [Errno 2] No such file or directory: 'C:/RCTemp/Details.xslm'
And this is my code:
import os
import shutil
dest_dkfrontend = 'C:/RhodeCode/11_Detailkonzept_Frontend/'
for filename in source:
if filename.startswith('Details'):
print('Files found ' + filename)
shutil.move("C:/RhodeCodeTemp/" + filename, dest_dkfrontend)
Can anyone help please?

Trouble moving files from folder to folder python

I am having trouble moving files from one folder to another. I have written this simple code:
import os
import shutil
movePath = "C:\\Users\\BWhitehouse\\Documents\\GVRD\\MonthlySummary_03\\SCADA"
destPath = "I:\\eng\\GVRD\\Rain_Gauges\\MonthlyDownloads\\2014-03"
for dirpath, dirs, files in os.walk(movePath):
for file in files:
if file.endswith('.xls'):
shutil.copy(file, destPath)
And this is the error I am getting:
Traceback (most recent call last):
File "C:\Python34\test.py", line 12, in <module> shutil.copy(file, destPath)
File "C:\Python34\lib\shutil.py", line 228, in copy copyfile(src, dst, follow_symlinks=follow_symlinks)
File "C:\Python34\lib\shutil.py", line 107, in copyfile with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'BU07-201403.xls'
If anyone could help me out that would be greatly appreciated!
The file variable is just the name, to get the full path add it to the dirpath variable:
shutil.copy( os.path.join(dirpath, file), destPath )
Do you have full access to these folders? First check it out.
Start Python as Administrator by right-clicking, when you try to start the script.
I had the same problem. I solved the problem in this way.

Categories

Resources