按文件名通配符打开文件

gre*_*reg 22 python filenames file wildcard

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

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

f = open('F:\text\somefile.txt', 'r')
for line in f:
    print line,
Run Code Online (Sandbox Code Playgroud)

我之前检查过glob模块,但我无法弄清楚如何对文件做任何实际操作.这是我想出来的,而不是工作.

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

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

Uku*_*kit 34

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,
Run Code Online (Sandbox Code Playgroud)

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

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

  • 在第二个代码片段中它应该是:使用open(文件,'r')作为f :(最好使用与'file'不同的变量名称) (3认同)

Oca*_*tal 8

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

文件通配符

然后你只需在这个列表上执行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,
Run Code Online (Sandbox Code Playgroud)


小智 5

此代码解释了初始问题中的两个问题:在当前目录中查找 .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)
Run Code Online (Sandbox Code Playgroud)