Open file by filename wildcard Open file by filename wildcard python python

Open file by filename wildcard


import osimport repath = "/home/mypath"for filename in os.listdir(path):    if re.match("text\d+.txt", filename):        with open(os.path.join(path, filename), 'r') as f:            for line in f:                print line,

Although you ignored my perfectly fine solution, here you go:

import globpath = "/home/mydir/*.txt"for filename in glob.glob(path):    with open(filename, 'r') as f:        for line in f:            print line,


You can use the glob module to get a list of files for wildcards:

File Wildcards

Then you just do a for-loop over this list and you are done:

filepath = "F:\irc\as\*.txt"txt = glob.glob(filepath)for textfile in txt:  f = open(textfile, 'r') #Maybe you need a os.joinpath here, see Uku Loskit's answer, I don't have a python interpreter at hand  for line in f:    print line,


This code accounts for both issues in the initial question: seeks for the .txt file in the current directory and then allows the user to search for some expression with the regex

#! /usr/bin/python3# regex search.py - opens all .txt files in a folder and searches for any line# that matches a user-supplied regular expressionimport re, osdef search(regex, txt):    searchRegex = re.compile(regex, re.I)    result = searchRegex.findall(txt)    print(result)user_search = input('Enter the regular expression\n')path = os.getcwd()folder = os.listdir(path)for file in folder:    if file.endswith('.txt'):        print(os.path.join(path, file))        txtfile = open(os.path.join(path, file), 'r+')        msg = txtfile.read()search(user_search, msg)