简体   繁体   English

按文件名通配符打开文件

[英]Open file by filename wildcard

I have a directory of text files that all have the extension .txt . 我有一个文本文件目录,都有扩展名.txt My goal is to print the contents of the text file. 我的目标是打印文本文件的内容。 I wish to be able use the wildcard *.txt to specify the file name I wish to open (I'm thinking along the lines of something like F:\\text\\*.txt ?), split the lines of the text file, then print the output. 我希望能够使用通配符*.txt来指定我想要打开的文件名(我正在考虑像F:\\text\\*.txt ?这样的行),拆分文本文件的行,然后打印输出。

Here is an example of what I want to do, but I want to be able to change somefile when executing my command. 这是我想要做的一个例子,但我希望能够在执行命令时更改somefile

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

I had checked out the glob module earlier, but I couldn't figure out how to actually do anything to the files. 我之前检查过glob模块,但我无法弄清楚如何对文件做任何实际操作。 Here is what I came up with, not working. 这是我想出来的,而不是工作。

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

lines = string.split(txt, '\n') #AttributeError: 'list' object has no attribute 'split'
print lines
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,

You can use the glob module to get a list of files for wildcards: 您可以使用glob模块获取通配符的文件列表:

File Wildcards 文件通配符

Then you just do a for-loop over this list and you are done: 然后你只需在这个列表上执行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,

This problem just came up for me and I was able to fix it with pure python: 这个问题刚刚出现,我能用纯python修复它:

Link to the python docs is found here: 10.8. 链接到python文档可在此处找到: 10.8。 fnmatch — Unix filename pattern matching fnmatch - Unix文件名模式匹配

Quote: "This example will print all file names in the current directory with the extension .txt:" Quote:“此示例将打印当前目录中扩展名为.txt的所有文件名:”

import fnmatch
import os

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

Check out "glob — Unix style pathname pattern expansion" 看看“glob - Unix风格的路径名模式扩展”

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM