Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open file by filename wildcard

I have a directory of text files that all have the extension .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.

Here is an example of what I want to do, but I want to be able to change somefile when executing my command.

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. 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 
like image 868
greg Avatar asked Feb 16 '11 07:02

greg


People also ask

How do you use a wildcard in a filename?

When you have a number of files named in series (for example, chap1 to chap12) or filenames with common characters (like aegis, aeon, and aerie), you can use wildcards (also called metacharacters) to specify many files at once. These special characters are * (asterisk), ? (question mark), and [ ] (square brackets).

What is wildcard file path?

When using wildcards in paths for file collections: * is a simple, non-recursive wildcard representing zero or more characters which you can use for paths and file names. ** is a recursive wildcard which can only be used with paths, not file names. Multiple recursive expressions within the path are not supported.

How do you use wildcards to search files and folders?

You can use your own wildcards to limit search results. You can use a question mark (?) as a wildcard for a single character and an asterisk (*) as a wildcard for any number of characters. For example, *. pdf would return only files with the PDF extension.

What is the use of * wild card character when we search a file?

The asterisk ( * ) Use it when searching for documents or files for which you have only partial names. For most web search engines, wildcards increase the number of your search results. For example, if you enter running as the search term, the search will return only documents with that one word.


1 Answers

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, 
like image 53
Uku Loskit Avatar answered Sep 19 '22 02:09

Uku Loskit