How to detect specific text in a string

Asked

Viewed 77 times

0

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

In this example, the "text": 100

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

I am wanting to develop this program, to delete files. Let’s assume that I have the files: "T100.txt", "A100.txt", "B100.txt". I want it to delete every 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")
  • In the title or file name ?

  • File name, I ended up confusing :x

1 answer

1

Your code didn’t make much sense, even though it wasn’t meant to be, it was just to try to illustrate. A possible solution, since it is working with files is to use the function glob.glob to get the files that obey a certain regular expression. With regular expression it is possible to check if a certain value exists in the file name.

For example, if you need to search all the scans that have the number 100 in the name, inside the directory arquivos, 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 package pathlib.

from pathlib import Path

for arquivo in Path('arquivos').glob('.*100.*'):
    arquivo.unlink()
  • That’s right, my goal was to try to illustrate.

  • I created a folder with the name "files" on the desktop, and put some files with "100" in the file name. I checked the program, it did not delete the files.

  • But your script is running on the desktop?

  • Yes, I cloned it to run on the desktop, because that’s where the folder is. But then I put the script in the folder, and it still didn’t work. I used the second solution (python 3.4).

  • Try to put ./arquivos

  • It didn’t work. If you add something, I’m using windows 7.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.