Search code examples
pythonregexglobsys

Make a file searching program that accepts a single regular expression with sys.argv.


I need to make a program that does exactly what the title states. I need my program to search through all the current files and all sub directories to see if any files match the pattern. If any files match the pattern, the whole pathname for the file should be printed on the screen.

I have some of this completed, however some parts may not make sense since I copied and pasted some parts from examples given to me in class:

#!/usr/bin/env python

import re, glob, sys, os
if (len(sys.argv) < 2):
        print("You need an argument.")
        sys.exit(0)

var = sys.argv(1)

#re.search(var,

data = os.walk(".")
for tup in data:
        dirname = tup[0]
        dirlist = tup[1]
        dirlist = tup[2]

        for file in filelist:
                fullname = os.path.join(dirname, file)
                username = owner(fullname)
                if re.data:
                print(os.path.abspath(os.path.join(username, fullname)))

Basically, when I run the program in Linux I need to type the name of the program and then an argument right afterwards. That argument is the name of the file I want to search for. So if I typed "./lab7.py .txt" I should expect the program to return any .txt files. I am still a beginner and the answer may seem pretty obvious to some of you, but I just can't seem to get that final step needed to make this program run the way it should. Any help is appreciated, thank you.


Solution

  • Your .txt argument is not meant to be a regular expression but a simple extension, so you don't need the regular expression package.

    Here's my version. Since it can be an extension but also a part of the filename, just use in. I've also simplified the owner() part which made no sense (apart from that your code was close)

    import os,sys
    
    if (len(sys.argv) < 2):
            print("You need an argument.")
            sys.exit(0)
    
    var = sys.argv[1]
    
    for root,dirs,files in os.walk("."):
        for f in files:
            if var in f:
                fullname = os.path.join(root, f)
                print(os.path.abspath(fullname))
    

    If extension matches, the full filepath is printed. Also works in sub-directories.