Sunday, April 28, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  8] [ 0]  / answers: 1 / hits: 150757  / 1 Year ago, fri, november 18, 2022, 6:38:53

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()

More From » python

 Answers
2

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.

[#29209] Sunday, November 20, 2022, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
steaocyte

Total Points: 345
Total Questions: 122
Total Answers: 121

Location: Spain
Member since Wed, Nov 23, 2022
1 Year ago
steaocyte questions
;