Python: How to use RegEx in an if statement?

后端 未结 5 2072
鱼传尺愫
鱼传尺愫 2020-12-25 10:06

I have the following code which looks through the files in one directory and copies files that contain a certain string into another directory, but I am trying to use Regula

5条回答
  •  不思量自难忘°
    2020-12-25 10:28

    First you compile the regex, then you have to use it with match, find, or some other method to actually run it against some input.

    import os
    import re
    import shutil
    
    def test():
        os.chdir("C:/Users/David/Desktop/Test/MyFiles")
        files = os.listdir(".")
        os.mkdir("C:/Users/David/Desktop/Test/MyFiles2")
        pattern = re.compile(regex_txt, re.IGNORECASE)
        for x in (files):
            with open((x), 'r') as input_file:
                for line in input_file:
                    if pattern.search(line):
                        shutil.copy(x, "C:/Users/David/Desktop/Test/MyFiles2")
                        break
    

提交回复
热议问题