簡體   English   中英

按文件名通配符打開文件

[英]Open file by filename 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
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,

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

這個問題剛剛出現,我能用純python修復它:

鏈接到python文檔可在此處找到: 10.8。 fnmatch - Unix文件名模式匹配

Quote:“此示例將打印當前目錄中擴展名為.txt的所有文件名:”

import fnmatch
import os

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

看看“glob - Unix風格的路徑名模式擴展”

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

此代碼解決了初始問題中的兩個問題:在當前目錄中搜索.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