4

Following code is to read all files in download directory,but when i execute this code it won't print(display), what is wrong with this code..?

import glob   
path = '/home/mypc/download/*.html'   
files=glob.glob(path)   
for file in files:     
    f=open(file, 'r')  
    f.readlines()   
    f.close() 
1
  • Can It be migrated to stackoverflow.
    – Naive
    May 31, 2017 at 12:53

4 Answers 4

8

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.
4

You may want to use at least one print. For example:

#!/usr/bin/env python

import glob   
path = '/home/mypc/download/*.html'   
files=glob.glob(path)   
for file in files:     
    f=open(file, 'r')  
    print '%s' % f.readlines()   
    f.close()
    #if you want to print only the filenames, use 'print file' instead of three previous lines

And please read some documentation about Input and Output in Python.

0
1

You have only written code to read the files, not to print the contents. If that is what you want to do you can replace

f.readlines() 

with:

for line in f:
    print line 

Hope that helps.

1

I you want to display the file names you need to use the print command

import glob   
path = '/home/mypc/download/*.html'   
files=glob.glob(path)   
for file in files: 
    print file

Not the answer you're looking for? Browse other questions tagged .