【问题标题】:Open file by filename wildcard通过文件名通配符打开文件
【发布时间】:2011-06-28 03:57:01
【问题描述】:

我有一个文本文件目录,它们都具有扩展名.txt。我的目标是打印文本文件的内容。我希望能够使用通配符*.txt 来指定我希望打开的文件名(我正在考虑类似F:\text\*.txt 的内容?),拆分文本文件的行,然后打印输出。

这是我想要做的一个例子,但我希望能够在执行我的命令时更改somefile

f = open('F:\text\somefile.txt', 'r')
for line in f:
    print line,

我之前检查了 glob 模块,但我不知道如何对文件进行实际操作。这是我想出的,不工作。

filepath = "F:\irc\as\*.txt"
txt = glob.glob(filepath)

lines = string.split(txt, '\n') #AttributeError: 'list' object has no attribute 'split'
print lines

【问题讨论】:

    标签: python file filenames wildcard


    【解决方案1】:
    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,
    

    虽然你忽略了我完美的解决方案,但你继续吧:

    import glob
    path = "/home/mydir/*.txt"
    for filename in glob.glob(path):
        with open(filename, 'r') as f:
            for line in f:
                print line,
    

    【讨论】:

    • 在第二个代码 sn-p 中应该是:with open(file,'r') as f: (也是一个比 'file' 更好地使用不同变量名的挑剔)
    【解决方案2】:

    您可以使用 glob 模块获取通配符的文件列表:

    File Wildcards

    然后你只需在这个列表上执行一个 for 循环就完成了:

    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,
    

    【讨论】:

    • 正如我所说,你必须遍历你从 glob.glob 中得到的列表:filepath = "F:\irc\as\*.txt" txt = glob.glob(filepath) for textfile in txt: f = open(textfile, 'r') for line in f: print line,
    • os.path.join 不需要,因为 glob.glob 提供了完整路径。还可以考虑使用 with 表达式,在您的解决方案中,文件句柄没有关闭。自动执行此操作:)
    【解决方案3】:

    此代码解决了最初问题中的两个问题:在当前目录中查找 .txt 文件,然后允许用户使用正则表达式搜索某些表达式

    #! /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)
    

    【讨论】:

      【解决方案4】:

      查看“glob — Unix 风格的路径名模式扩展”

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

      【讨论】:

      • @greg 你为什么在 glob.glob 的结果上尝试 string.split()? glob.glob 返回匹配文件名的列表。只需遍历列表即可。您仍然需要打开每个文件并阅读它。
      【解决方案5】:

      这个问题刚刚出现在我身上,我可以用纯 python 解决它:

      可在此处找到指向 python 文档的链接:10.8. fnmatch — Unix filename pattern matching

      引用:“此示例将打印当前目录中所有扩展名为 .txt 的文件名:”

      import fnmatch
      import os
      
      for file in os.listdir('.'):
          if fnmatch.fnmatch(file, '*.txt'):
              print(file)
      

      【讨论】:

      • '.'在 os.listdir 中表示“当前目录”。很高兴知道您是否需要在其他地方指定目录。
      猜你喜欢
      • 1970-01-01
      • 2016-07-05
      • 2019-06-08
      • 2017-05-08
      • 2012-04-21
      • 2018-08-22
      • 2012-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多