按文件名通配符打开文件

时间:2011-02-16 07:12:29

标签: python file filenames wildcard

我有一个文本文件目录,所有文件都有.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

5 个答案:

答案 0 :(得分:26)

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,

答案 1 :(得分:6)

您可以使用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,

答案 2 :(得分:2)

查看“glob - Unix样式路径名模式扩展”

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

答案 3 :(得分:2)

这个问题刚刚出现,我能用纯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)

答案 4 :(得分:0)

此代码解决了最初问题中的两个问题:在当前目录中查找.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)