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
Check out "glob — Unix style pathname pattern expansion"
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
You can use the glob module to get a list of files for wildcards:
File Wildcards
Then you just do a for-loop over this list and you are done:
This problem just came up for me and I was able to fix it with pure python:
Link to the python docs is found here: 10.8. fnmatch — Unix filename pattern matching
Quote: "This example will print all file names in the current directory with the extension .txt:"
Although you ignored my perfectly fine solution, here you go: