Open file by filename wildcard

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

提交回复
热议问题