Open file by filename wildcard

后端 未结 5 763
耶瑟儿~
耶瑟儿~ 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:38

    Check out "glob — Unix style pathname pattern expansion"

    http://docs.python.org/library/glob.html

    0 讨论(0)
  • 2020-12-13 14:42

    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,
    
    0 讨论(0)
  • 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,
    
    0 讨论(0)
  • 2020-12-13 14:50

    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 expression
    
    import re, os
    
    def 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)
    
    0 讨论(0)
  • 2020-12-13 14:57

    This problem just came up for me and I was able to fix it with pure python:

    Link to the python docs is found here: 10.8. fnmatch — Unix filename pattern matching

    Quote: "This example will print all file names in the current directory with the extension .txt:"

    import fnmatch
    import os
    
    for file in os.listdir('.'):
        if fnmatch.fnmatch(file, '*.txt'):
            print(file)
    
    0 讨论(0)
提交回复
热议问题