How to import files using REGEX?

Asked

Viewed 63 times

0

Good afternoon Everybody, all right?

I have a question in regex in python.

I want to create a script to open files without informing its format may be

pdf, txt, jpg, png, among others... However, I just want to specify the name of the image, without informing its format (informing the format inside the regex). Any hint of solution?

1 answer

0


You can create a Pattern with the desired name, and possible extensions. Supposing you wish to search for png., or jpg image. or gif image. within c:/test

import re
import os
padrao = r'imagem\.(png|jpg|gif)'
base_dir = 'c:/teste/'
for arquivo in os.listdir():
    if re.match(padrao, arquivo):
        with open(base_dir + arquivo) as reader:
            print(reader.read())
  • Thanks Moises, it worked, however, I can not read the file, it just displays the format, is there the possibility of it display? if it is a . txt or . pdf? I made the following change in code : import re import os standard = r'attendance.(png|jpg|gif|txt|pdf) ' for file in os.listdir('C:/Users/v_lop/Desktop/Import/'): if re.match(default, file): print(file.file.read()) # in read it reports error : 'str' Object has no attribute 'file'

  • in the example I used print only to display the name of the found file. If you want to read the contents of this file, you will need to exchange the print for open(). Edited for your understanding

  • Thanks buddy, it worked!

Browser other questions tagged

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