Steve Arguin
Steve Arguin

Reputation: 23

Delete all files within a director if they contain string []

I have a folder with 5 .txt files:

100240042.txt
102042044.txt
016904962.txt
410940329.txt
430594264.txt

One contains only different types of fruit (e.g. apple, banana, orange, ect.). However, the others all contain 'chicken'. These must be deleted, leaving only the fruit list left.

So far, I've tried 4 different solutions

Attempt 0

import os
for filename in os.listdir(r'C:\Users\Steve\AppData\Local\Programs\Python\Python37-32\Fruits'):
    f = open(filename)
    for line in filename:
        if 'chicken' in line:
            found=true
            os.remove(filename)
    f.close()

Attempt 1

import os
for file in os.listdir(r'C:\Users\Steve\AppData\Local\Programs\Python\Python37-32\Fruits'):
    open(file, 'r')
    f.read()
    find('chicken')
    os.remove()
    f.close()

Attempt 2

import os
for file in os.listdir(r'C:\Users\Steve\AppData\Local\Programs\Python\Python37-32\Fruits'):
    open(file, 'r')
    f.read()
    find('chicken')
    os.remove()
    f.close()

Attempt 3

import os
for file in os.listdir(r'C:\Users\Steve\AppData\Local\Programs\Python\Python37-32\Fruits'):
    if 'chicken' in open(file).read():
    os.remove(file)
    f.close()

I think this is a relatively simple problem, but I keep getting the following errors:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
FileNotFoundError: [Errno 2] No such file or directory: '100240042.txt'

Upvotes: 1

Views: 1360

Answers (2)

adrtam
adrtam

Reputation: 7211

I see other problems but let me just address what you asked:

os.remove(filename)

This is executed at the current directory. Usually the directory you run your program. But if you try to run command rm filename on your shell, you will also see errors because the file is actually on another directory. What you want to do is this:

open(os.path.join(r'C:\Users\Steve\AppData\Local\Programs\Python\Python37-32\Fruits', filename))

and also:

os.remove(os.path.join(r'C:\Users\Steve\AppData\Local\Programs\Python\Python37-32\Fruits', filename))

So your code should look like the following:

DIR = r'C:\Users\Steve\AppData\Local\Programs\Python\Python37-32\Fruits'
for filename in os.listdir(DIR):
    found = False
    with open(os.path.join(DIR, filename)) as f:
        for line in f:
            if 'chicken' in line:
                found = True
                break
    if found:
        os.remove(os.path.join(DIR, filename))

Upvotes: 2

Saif Asif
Saif Asif

Reputation: 5658

You have to construct the full path of the file. If you see the error message,

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

It is trying to open the file relative to the path of the script. In short, its looking for this file in the same directory as your script.

For getting absolute path, do something like

os.path.abspath("myFile.txt")

Upvotes: 0

Related Questions