Open file by filename wildcard

后端 未结 5 765
耶瑟儿~
耶瑟儿~ 2020-12-13 14:29

I have a directory of text files that all have the extension .txt. My goal is to print the contents of the text file. I wish to be able use the wildcard *

5条回答
  •  借酒劲吻你
    2020-12-13 14:43

    import os
    import re
    path = "/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 glob
    path = "/home/mydir/*.txt"
    for filename in glob.glob(path):
        with open(filename, 'r') as f:
            for line in f:
                print line,
    

提交回复
热议问题