How can I delete multiple files using a Python script? - python

I am playing around with some python scripts and I ran into a problem with the script I'm writing. It's supposed to find all the files in a folder that meets the criteria and then delete it. However, it finds the files, but at the time of deleting the file, it says that the file is not found.
This is my code:
import os
for filename in os.listdir('C:\\New folder\\'):
if filename.endswith(".rdp"):
os.unlink(filename)
And this is the error I get after running it:
FileNotFoundError: [WinError 2] The system cannot find the file specified:
Can somebody assist with this?

os.unlink takes the path to the file, not only its filename. Try pre-pending your filename with the dirname. Like this
import os
dirname = 'C:\\New folder\\'
for filename in os.listdir(dirname):
if filename.endswith(".rdp"):
# Add your "dirname" to the file path
os.unlink(dirname + filename)

You could alternatively use os.walk, however it might go deeper than you want:
import os
for root, sub, file in os.walk("/media/"):
if file.endswith(".rdp"):
os.unlink(f'{root}/{file}')

Related

How are paths meant to be denoted on for Biopython on mac?

I am trying to run a basic biopython script to rename sequences within a fasta file. I have only ever ran this on a server; i am trying to do it on my macbook but I can't work out what the correct path to the file should be.
on the server is worked as follows:
original_file = r”/home/ggb_myname/Documents/Viromex/Viromex.contigs.fa”
I am trying to do the same thing on my mac with
original_file = r"/Users/u2188165/Documents/Home/Post-qiime/dna-sequences.fasta"
and it returns the error
FileNotFoundError: [Errno 2] No such file or directory: '/Users/u2188165/Documents/Home/Post-qiime/dna-sequences.fasta
I know this is probably basic, but I can't find the correct way to write the path, either on my own or online.
Try using libraries like pathlib and os. Makes your code more modular and os independent to use.
from pathlib import Path
import os
dir ="/Users/u2188165/Documents/Home/Post-qiime"
file= "dna-sequences.fasta"
full_path = os.path.join(str(Path(dir)), file)
Or even try drill down approach for more versatility.
from pathlib import Path
import os
path_drill = ["Users","u2188165","Documents","Home","Post-qiime"]
file= "dna-sequences.fasta"
full_path = str(Path(os.path.join(*path_drill, file)))
How/Where you want to store this is upto your imagination and requirements.
Happy coding!

FileNotFoundError: [Errno 2] No such file or directory: 'demofile.txt'

can someone tell me why when I want to open a text file with python
my output is FileNotFoundError: [Errno 2] No such file or directory: 'demofile.txt'
even though the file is already in the same folder and the writing is correct.
and this is my code
f = open("demofile.txt", "r")
print(f.read())
thank you before
The path of the Python file and the current working directory can differ. open uses the current working directory if you use a relative path. The obvious fix is to use an absolute path. But then you will have to edit the code each time you copy the script to a different folder.
You can use pathlib to create an absolute path based on the current running scripts location. Put this in a Python script, run it and look at the result.
import pathlib
print(pathlib.Path(__file__).parent)
print(pathlib.Path(__file__).parent / 'demofile.txt')
print(pathlib.Path(__file__).parent / 'data' / 'demofile.txt')
So your code can be changed to
filepath = pathlib.Path(__file__).parent / 'demofile.txt'
with open(filepath, 'r') as f:
print(f.read())
Try using with
with open("demofile.txt","r") as f:
f.read()
Maybe, You are executing python file with absolute path that's why FileNotFound.
Try with absolute path. Like, c:\files\demofile.txt
I solved the problem with the answer of Mathias, I had the same problem but with an image, then you need to write
import pathlib
print(pathlib.Path(__file__).parent)
print(pathlib.Path(__file__).parent / 'name_of_your_file.extension')
print(pathlib.Path(__file__).parent / 'data' / 'name_of_your_file.extension')
already done the correct answer is to use the name of the specific folder where the text files are located
thank you very much, everyone

Find a file recursively using python

I have the below files located at some location in RHEL machine.
temp_file2.txt
temp_file3.txt
Looking for a python script to find above files recursively in all directories(I used a wild card, but it didn't work), and print a message if the file exists or not.
The below code snippet returns Nothing
import glob
for filename in glob.iglob('*/*.txt', recursive=True):
print(filename)
It returns the file name if it exists only in the current working directory
import glob
for filename in glob.iglob('.txt', recursive=True):
print(filename)
This approach seems to have worked for me, using python3.6
import glob
for f in glob.iglob('./**/*.yml', recursive=True):
print(f)
I was also able to use os.getcwd() + '/**/*.yml'. It appears there must be a directory definition at the start of the glob.

python os.rename directory not empty

I'm trying to do mv test-dir/* ./ but in python. I have written the following code but throws OSError: [Errno 66] Directory not empty:
import os
os.rename(
os.getcwd() + '/test-dir',
os.path.abspath(os.path.expanduser('.')))
You may want to use shutil.move() to iteratively move the files from a directory to another.
For example,
import os
import shutil
from_dir = os.path.join(os.getcwd(),"test-dir")
to_dir = os.path.abspath(os.path.expanduser('.'))
for file in os.listdir(from_dir):
shutil.move(os.path.join(from_dir, file), to_dir)
You're telling the OS to move test-dir, not its contents. It would normally replace the target (. in this case) but that target obviously isn't empty, so the implicit rmdir fails. Even if it weren't empty, it's likely impossible to remove or replace the . name.
The shell * is a glob, which would expand to each thing within test-dir, which you could move individually; however, you'd want to transfer their name to the target directory, i.e. test-dir/foobar to ./foobar. os.path.basename can help you extract that portion.

How do I copy all files of one specific type from a folder to another folder in Python

Im trying to copy a numerous amount of .txt files from one folder to another using a Python script. I dont want to copy one single file at a time, and im not even sure exactly how many txt files are present in the folder. I am looking to scan the folder and copy all text files from it to another folder. I have already tried doing this using the shutil and os libraries to no avail. Can someone please help?
import os
import shutil
def start():
dest = "C:/Users/Vibhav/Desktop/Txt"
source = "C:/Users/Vibhav/Desktop/Games"
for file in os.listdir("C:/Users/Vibhav/Desktop/Games"):
if file.endswith(".txt"):
shutil.copy2(dest,source)
This is what I have tried doing, but it doesnt work for me. I keep getting this error
PermissionError: [Errno 13] Permission denied: 'C:/Users/Vibhav/Desktop/Games'
It would really help me if someone could help me out
Main mistake: you're trying to copy the directory, not the file.
Rewriting using glob.glob to get pattern filtering + absolute path sounds the best option:
def start():
dest = "C:/Users/Vibhav/Desktop/Txt"
source = "C:/Users/Vibhav/Desktop/Games"
for file in glob.glob(os.path.join(source,"*.txt")):
shutil.copy2(file,dest)

Categories

Resources