Changing the location of text file from one folder to another - python

I was trying to execute a code in spyder to change a location of text file from one folder to another. But I am repeatedly getting the error that is "File Not Found" even though file exists in the folder. I want to resolve this issue. Can any one help me with it?
import os
from os import path
import shutil
src = "Desktop\This PC\Windows (C:)\new1\test.txt"
dst = "Desktop\This PC\Windows (C:)\new2"
files = [i for i in os.listdir(src) if i.startswith("CTASK") and path.isfile(path.join(src, i))]
for f in files:
shutil.copy(path.join(src, f), dst)

Related

Trying to pass files from a subfolder to a new folder after Filtering

I am trying to make a code that allows me to copy files from various subfolders to a new folder. The main problem and why it wasn't a straight forward thing to deal with since the beginning is that all the files start the same and end the same, just 1 letter changes in the file that I need.
I keep getting an error saying: "FileNotFoundError: [Errno 2] No such file or directory: '20210715 10.1_Plate_R_p00_0_B04f00d0.TIF'"
So far this is what I have:
import os,fnmatch, shutil
mainFolder = r"E:\Screening\202010715\20210715 Screening"
dst = r"C:\Users\**\Dropbox (**)\My PC\Desktop\Screening Data\20210715"
for subFolder in os.listdir(mainFolder):
sf = mainFolder+"/"+subFolder
id os.path.isdir(sf):
subset = fnmatch.filter(os.listdir(sf), "*_R_*")
for files in subset:
if '_R_' in files:
shutil.copy(files, dst)
PLEASE HELP!
The issue is that you aren't providing the full path to the file to shutil.copy, so it assumes the file exists in the folder you are running the script from. Another issue the code has, is that the subset variable gets replaced in each loop before you are able to copy the files you matched in the next loop.
import os, fnmatch, shutil
mainFolder = r"E:\Screening\202010715\20210715 Screening"
dst = r"C:\Users\**\Dropbox (**)\My PC\Desktop\Screening Data\20210715"
matches = [] # To store the matches
for subFolder in os.listdir(mainFolder):
sf = mainFolder + "/" + subFolder
if os.path.isdir(sf):
matches.extend([f'{sf}/{file}' for file in fnmatch.filter(os.listdir(sf), "*_R_*")]) # Append the full path to the file
for files in matches:
shutil.copy(files, dst)

python- moving files and checking duplicate names

I'm trying to make a code that can move files from one folder to another.
For instance, I have files named 0001.jpg, 0002.jpg ... and so on in /test1/ folder and want to move those files to /test3/ folder if the same file name doesn't exist in /test2/.
So, if there's 0001.jpg both in folder /test1/ and /test2/ the file in /test1/ won't be moved to /test3/ folder but if there's 0002.jpg in /test1/ and not in /test2/, it moves to /test/3.
I've tried to write the code on my own but it won't work.
Can you please help with this?
Thanks in advance!
import os
import shutil
def Move_files(root_path, refer_path, out_path) :
root_path_list= [file for file in os.listdir(root_path)]
refer_path_list= [file for file in os.listdir(refer_path)]
for file in root_path_list:
if refer_path_list in root_path_list:
shutil.move(os.path.join(os.listdir(root_path, file)),os.path.join(os.listdir(refer_path, file)))
if __name__ == '__main__' :
Move_files("D:\\Dataset\\test1", "D:\\Dataset\\test2", "D:\\Dataset\\test3")
Updated: You can check if the file exists in your other directory using os.path.exists, and then only moving it if it does not already exist in /test2/:
if not os.path.exists(os.path.join(refer_path, file)):
shutil.move(os.path.join(os.listdir(root_path, file)),os.path.join(os.listdir(refer_path, file)))
Also, os.listdir only accepts one argument, the path to the directory of which you want to list the files. I think you want to change your shutil.move statement to this: shutil.move(os.path.join(root_path, file),os.path.join(out_path, file))
Try this
import os
import shutil
def Move_files(root_path, refer_path, out_path) :
root_path_list= [file for file in os.listdir(root_path)]
refer_path_list= [file for file in os.listdir(refer_path)]
for file in root_path_list:
if file not in refer_path_list:
shutil.move(os.path.join(os.listdir(root_path, file)),os.path.join(os.listdir(out_path, file)))
if __name__ == '__main__' :
Move_files("D:\\Dataset\\test1", "D:\\Dataset\\test2", "D:\\Dataset\\test3")
You can use set to find the difference between the file lists. I added an isfile check to ignore subdirectories (e.g., the "." and ".." directories in linux) and since shutil.move accepts a target directory, there is no need to build the target file name.
import os
import shutil
def Move_files(root_path, refer_path, out_path) :
root_files = set(filename for filename in os.listdir(root_path)
if os.path.isfile(filename))
refer_files = set(filename for filename in os.listdir(refer_path)
if os.path.isfile(filename))
move_files = root_files - refer_files
for file in move_files:
shutil.move(os.path.join(root_path, file), out_path)
if __name__ == '__main__' :
Move_files("D:\\Dataset\\test1", "D:\\Dataset\\test2", "D:\\Dataset\\test3")

Python, Windows. Addressing folder in parent directory

I have a "main" folder with two folders inside: "Data" and "Code". "Data" folder contains "limited_scope" folder with .txt files. From "Code" folder I run my_code.py file with lines:
import os
directory_path = '..\\Data\\limited_scope\\'
directorie = sorted(os.listdir(directory_path))
And get the error:
FileNotFoundError: [WinError 3] The system cannot find the path specified: '..\\Data\\limited_scope\\'
When I change to:
directory_path = 'C:\\Users\\myname\\Documents\\main\\Data\\limited_scope\\'
the error disappears.
Can anyone tell the reason of this error?
Your current working directpry while executing the my_code.py should be the Code directory, then this will work.
Otherwise you can try below code which will use my_code.py's folder and use it:
import os
current_dir = os.path.dirname(__file__)
directory_path = os.path.join(current_dir,'..\\Data\\limited_scope\\')
directorie = sorted(os.listdir(directory_path))

Monitor a folder for .jpg added, autoprint using CUPS, move same .jpg to another folder

I am trying to create an auto postcard print script on my Raspberry Pi 3B using Python 2.7. I want the script to continually run in the background checking for any new .jpg files that is dropped into the folder, autoprints ALL .jpg dropped in the folder to a printer using CUPS/pycups, and then move the .jpg to another folder called "DONE." The following code does not work: but gives a "lp: Error - unable to access "test.jpg" - No such file or directory". Appreciate any help!
#!/usr/bin/env python
import cups
import os
import time
import subprocess
from glob import glob
import shutil
conn = cups.Connection()
printers = conn.getPrinters()
printer_name = printers.keys()[0]
cups.setUser('pi')
path_to_watch = ('/home/pi/Desktop/PRINT/')
source = path_to_watch
dest1 = '/home/pi/Desktop/DONE'
before = dict ([(f, None) for f in os.listdir (path_to_watch)])
while 1:
time.sleep (10)
after = dict ([(f, None) for f in glob(path_to_watch + '*.jpg')])
added = [f for f in after if not f in before]
removed = [f for f in before if not f in after]
if added:
print "Added: ", ", ".join (added)
subprocess.Popen(["lp", "--"] + added).communicate()
shutil.move(source+f, dest1)
if removed: print "Removed: ", ", ".join (removed)
before = after
EDITED: This semi-works now thanks to #metatoaster for the printing part, but the moving to DONE folder does not work effectively. That is, when I first run the program, it does PRINT any .jpg already in the folder, then moves the .jpg files from the PRINT folder to DONE, but then when I dropped a NEW .jpg into the PRINT folder, it gives me this error, and exits the script:
File "print2.py", line 30, in <module>
shutil.move(source+f, dest1)
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: '/home/pi/Desktop/PRINT//home/pi/Desktop/PRINT/test.jpg'
Any further advice? Thanks!
The error lp is generating is because it can't find test.jpg in the current directory, which is likely the directory where you are running that Python script from. The reason for this is because the list of strings returned by os.listdir only has the name of the file of the directory, but not the full path itself.
>>> os.listdir('/tmp/foo/bar')
['file5.jpg', 'file4.jpg', 'file3.jpg', 'file2.jpg', 'file1.jpg', 'file5', 'file4', 'file3', 'file2', 'file1']
Note that all files are listed without the preceding dir, and not just jpg files like what you might want. One possible way to fix that is to join the path_to_watch value for each of the values returned by os.listdir (so that lp has the full, unambiguous path to the intended file) and also filter the result by jpg, but then I noticed you have glob imported. That module provides a glob function which should provide exactly what you need, try:
>>> from glob import glob
>>> glob('/tmp/foo/bar/*.jpg')
['/tmp/foo/bar/file5.jpg', '/tmp/foo/bar/file4.jpg', '/tmp/foo/bar/file3.jpg', '/tmp/foo/bar/file2.jpg', '/tmp/foo/bar/file1.jpg']
Note how the full path is included. To integrate this into your code, you may want to try:
before = dict ([(f, None) for f in glob(path_to_watch + '*.jpg')])

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)

Categories

Resources