Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, How do I check whether a file exists starting or ending with a substring?

I know about os.path.isfile(fname), but now I need to search if a file exists that is named FILEnTEST.txt where n could be any positive integer (so it could be FILE1TEST.txt or FILE9876TEST.txt)

I guess a solution to this could involve substrings that the filename starts/ends with OR one that involves somehow calling os.path.isfile('FILE' + n + 'TEST.txt') and replacing n with any number, but I don't know how to approach either solution.

like image 409
Michael Leong Avatar asked Jun 10 '17 02:06

Michael Leong


People also ask

How do you check if a string starts with a specific letter in Python?

The startswith() method returns True if a string starts with the specified prefix(string). If not, it returns False .


2 Answers

You would need to write your own filtering system, by getting all the files in a directory and then matching them to a regex string and seeing if they fail the test or not:

import re

pattern = re.compile("FILE\d+TEST.txt")
dir = "/test/"
for filepath in os.listdir(dir):
    if pattern.match(filepath):
        #do stuff with matching file

I'm not near a machine with Python installed on it to test the code, but it should be something along those lines.

like image 117
JordanOcokoljic Avatar answered Oct 21 '22 02:10

JordanOcokoljic


You can use a regular expression:

/FILE\d+TEST.txt/

Example: regexr.com.

Then you can use said regular expression and iterate through all of the files in a directory.

import re
import os

filename_re = 'FILE\d+TEST.txt'
for filename in os.listdir(directory):
    if re.search(filename_re, filename):
        # this file has the form FILEnTEST.txt
        # do what you want with it now
like image 38
Sumner Evans Avatar answered Oct 21 '22 01:10

Sumner Evans