How to detect specific text in a string

0

I want to make a program that detects if it has a specific "text" in the input entered by the user.

In this example, the "text": 100

I want it to detect this 100 (regardless of position) in the input. Example: test100 or 100test

I want to develop this program, to delete files. Let's say I have the files: "t100.txt", "a100.txt", "b100.txt". I want it to delete each file that contains "100" in the title.

import os 

#Arquivos
a1 = open('t100.txt', 'r+')
a2 = open('a100.txt', 'r+')
a3 = open('b100.txt', 'r+')

string = input('Você deseja excluir todos os arquivos que contém qual string: ')

if string[] == '100':
    print("Removendo os arquivos que contém '100' no título")
    os.remove()
else:
    print("Não há arquivos que contém '100' no título")
    
asked by anonymous 24.01.2018 / 23:57

1 answer

1

His code did not make much sense, even though he was not even supposed to do it, it was just to try to illustrate. One possible solution, since you are dealing with files, is to use the glob.glob function to grab files that obey a certain regular expression. With the regular expression you can check if a given value exists in the file name.

For example, if you need to fetch all variants that have the number 100 in the name, within the arquivos directory, you can do:

from os import remove
from glob import glob

for arquivo in glob('arquivos/.*100.*'):
    remove(arquivo)

Another solution, if you use Python 3.4+, is to use the pathlib package.

from pathlib import Path

for arquivo in Path('arquivos').glob('.*100.*'):
    arquivo.unlink()
    
25.01.2018 / 00:11