File identified but cannot be deleted - Python - python

So I'm trying to make the a program that deletes files which can be launched from the command lines. But when I run it, it fails and returns the following message: FileNotFoundError: [WinError 2] The system cannot find the file specified: 'test.txt'. Here's the code:
import sys
import os
num = int(sys.argv[1])
files = os.listdir(sys.argv[2])
for file in files[:num]:
print('Deleting '+file+'...')
os.remove(file)
The file is identified but it cannot be deleted.

You need to add the directory path back to the path:
import sys
import os
num = int(sys.argv[1])
files = os.listdir(sys.argv[2])
for file in files[:num]:
print('Deleting '+file+'...')
os.remove(os.path.join(sys.argv[2], file))
os.listdir will only return the basename of the file, whereas you'll need a relative or full path

Related

file does not exist when I want to move it

I'm preprocessing datas to apply deep learning on audio files. I have a directory of audio file (.wav) with differents length and my goal is to use 0 padding in order to have only 10 secondes files duration. I also want to move move files that are longer than 10 secondes in an other directory:
from pydub import AudioSegment
import os
import shutil
path_to_sound = r'my\path\to\sound'
path_to_export = r'my\path\to\export'
path_for_too_long = r'my\path\to\other_directory'
pad_ms= 10000
file_names=os.listdir(path_to_sound)
print(file_names) # ['30368.wav', '41348.wav', '42900.wav', '42901.wav', '42902.wav']
for name in file_names:
audio= AudioSegment.from_wav(os.path.join(path_to_sound, name))
if pad_ms > len(audio):
shutil.move(name,path_for_too_long )
else:
silence = AudioSegment.silent(duration=pad_ms-len(audio)+1)
padded = audio + silence
padded.export(os.path.join(path_to_export, name), format = 'wav')
When running this I got the following errors:
FileNotFoundError: [WinError 2] The specified file can not be found : '41348.wav' -> 'C:\\Users\\path_for_too_long\\41348.wav'
...
FileNotFoundError: [Errno 2] No such file or directory: '41348.wav'
I think the error is due to the way i'm using shutil.move()
shutil.move expects the full path, here you are providing the name which corresponds to the filename and not the file path.
You have to update the line:
shutil.move(name, path_for_too_long)
to:
shutil.move(os.path.join(path_to_sound, name), path_for_too_long)
Remark: if you are using Python 3.4+ you can use pathlib instead of os to handle paths. You can find 2 articles on this:
Why you should be using pathlib
No really, pathlib is great
before u delete,try to findout if is exist.
import os
path = ''
if os.path.exists(path):
func_to_delete()

what is the correct or best way to input a users home path address into a string?

Hello as the title says i am writing a program which copys data from chrome. my current code is
#library imports
import sys
import shutil
import os
import subprocess
#search and find requried files.
os.path.expanduser('~user') #search for user path
#Making directory
newpath = r'F:\Evidence\Chromium'
newpath = r'F:\Evidence\Chrome'
#Copy chrome file
original = r'%LOCALAPPDATA%\Google\Chrome\User Data\Default\History'
target = r'F:\Evidence\Chrome'
shutil.copyfile(original, target)
i get a error on the line original = r'%LOCALAPPDATA%\Google\Chrome\User Data\Default\History'
i assume the script cannot read %LOCALAPPDATA%\ and needs the correct user path ?
what code do i need to input the user directory on a windows PC?
for example C:\Users\(Script to find out this part)\AppData\Local\Google\Chrome\User Data\Default
Scripv3.py", line 25, in <module>
shutil.copyfile(original, target)
File "C:\Users\darks\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 261, in copyfile
with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst:
FileNotFoundError: [Errno 2] No such file or directory: '%LOCALAPPDATA%\\Google\\Chrome\\User Data\\Default\\History'
Use the pathlib library.
from pathlib import Path
original = Path.home() / "Google/Chrome/User data/Default/History"
target = Path("F:/Evidence/Chrome")
shutil.copyfile(origina, target)
What you want to do is use os.path.expandvars() function on original variable:
os.path.expandvars(r'%LOCALAPPDATA%')
Will return:
C:\Users\USERNAME\AppData\Local
Where USERNAME is the name of the current user.
So, ensure the variables are expanded for this path:
original = os.path.expandvars(original)
before using it in shutil.copy(original, target)

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')])

Unable to copy or move a file using python shutil

import shutil
import os
source = os.listdir("report")
destination = "archieved"
for files in source:
if files.endswith(".json"):
shutil.copy(files, destination)
I have the file named, 'a.json' inside the report folder report/a.json; however, the file is not moved/copied to the target folder
Console Error:
*** FileNotFoundError: [Errno 2] No such file or directory: 'a.json'
os.listdir() returns filenames and not paths. You need to construct the paths from the filenames before calling shutil.copy().
import shutil
import os
source_directory_path = "report"
destination_directory_path = "archived"
for source_filename in os.listdir(source_directory_path):
if source_filename.endswith(".json"):
# construct path from filename
source_file_path = os.path.join(source_directory_path, source_filename)
shutil.copy(source_file_path, destination_directory_path)

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