The readlines()
method of a file object returns a Python list. It does not automatically write on stdout the contents of the file: Python is a scripting language, but not a shell scriping language!
You should replace:
f.readlines()
with:
sys.stdout.write(f.read())
Note that I'm using read()
instead of readlines()
. As I said, readlines()
returns a list, but here we want to print a string -- and read()
does what we want: it reads the whole file and returns a string. It's not optimal when the file is huge (because it will use a huge amount of memory), but it works.
It's worth noting that you code is flawed. You said: following code is to read all files in download directory. Your code actually will attempt to read both files and directories ending with .html
. If your code finds a directory ending with .html
, it will loudly crash.
Lastly, you should prefer using the with
statement when opening files, especially when you are opening many files. The with
statement will ensure that the file is closed as soon as you have finished working with it, even if an error occurs.
Therefore your code should look like this:
import sys
import glob
import errno
path = '/home/mypc/download/*.html'
files = glob.glob(path)
for name in files: # 'file' is a builtin type, 'name' is a less-ambiguous variable name.
try:
with open(name) as f: # No need to specify 'r': this is the default.
sys.stdout.write(f.read())
except IOError as exc:
if exc.errno != errno.EISDIR: # Do not fail if a directory is found, just ignore it.
raise # Propagate other kinds of IOError.