0

I want to check if a file exists. So I use the following code :

if os.path.exists(filepath + "Piezometrie.xlsx"):
    try :
       # do something
    else:
        pass

When I want to check if a file contains some specific characters, I use :

piezo = filepath + "Piezometrie.xlsx"
texte = "zom"

if re.search(texte, piezo):
    print "ok"
else:
    print "ko"

But how could I do to check if a file that contains specific characters (like "zom" in this example) exists (by using regex) ?

Thank you very much !
Julien

Julien
  • 699
  • 3
  • 14
  • 30
  • But he is not searching in txt, he is searching in xlsx – Tales Pádua Sep 23 '16 at 13:54
  • Use glob: https://docs.python.org/3/library/glob.html – Casimir et Hippolyte Sep 23 '16 at 13:55
  • Are you trying to check the file *name* or the file *contents*? – jpmc26 Sep 23 '16 at 13:57
  • @A_Elric, @jpmc26: Look at the wording used by @Julien to describe the second code snippet. Apparently, the phrase "if a file contains some specific character" is meant to refer to the file name. Hence, he's asking not about the file content. If so, sokoli's answer should do. Or ``glob``, of course. – Schmuddi Sep 23 '16 at 14:08

1 Answers1

0

List all files in directory and check every one for text. For example: (pseudocode)

files = os.get_files_in_directory('/home/user/')
files_with_sth_in_name = [filename for filename in files if re.search(texte, piezo)

Or use something made for such job: https://docs.python.org/3/library/glob.html

sokoli
  • 501
  • 3
  • 10