You are looking for os.listdir. It will give you a list of all the file names in the specified directory, which defaults to the current directory. The reason that '*' does not work is that it is a command-line construct that is expanded by your shell. You can only really use it in a shell or script that supports that sort of expansion. Since open does not go through the shell, it tries to find a file actually named *. Also, open can only deal with one file at a time.
import os, os.path, re
os.chdir(r'/home/jay/data/')
files = os.listdir()
for name in files:
# Skip directories
if os.path.isdir(name):
continue
with open(name) as file:
for line in file:
line = line.rstrip()
if re.search('Model' , line):
print(line)
That being said, as a matter of personal preference, I generally avoid using os.chdir. Instead, I prefer specifying full paths using os.path.join. Here is your example rewritten to do that:
from os import listdir
from os.path import join, isdir
folder = '/home/jay/data'
files = listdir(folder)
for name in files:
name = join(folder, name)
# Skip directories
if isdir(name):
continue
with open(name) as file:
for line in file:
line = line.rstrip()
if 'Model' in line:
print(line)
I took the liberty of removing the regex completely since it only serves to slow things down in you have many files. If you do use a regex for some more complicated scenario, compile if before you use it using re.compile.
Furthermore, you are free to use relative paths here if you want. For example, if you are always running from /home/jay, you can set folder = 'data' instead of folder = '/home/jay/data' in the second example.
files = open(*)you wouldn't be getting anIOErrorbut rather aSyntaxError. Please post your actual code.print(line)`is also syntax error.No such file or directory: '/home/jay/Data/*'if your line really readsos.chdir(r'/home/jay/data/'). Please fix your code!