How do you read lines from all files in a directory?

Question:

I have two files in a directory. I’d like to read the lines from each of the files. Unfortunately when I try to do so with the following code, there is no output.

from pathlib import Path 

p = Path('tmp')
for file in p.iterdir():
   print(file.name)

functions.py
test.txt

for file in p.iterdir():
    f = open(file, 'r')
    f.readlines()
Asked By: jgg

||

Answers:

You should print data like this from text.py

count = 1
f = open(file, 'r')
Lines = f.readlines()
for line in Lines:
    count += 1
    print("Line {}: {}".format(count, line.strip()))

Output will look like:

Line 1: ...
Line 2: ...
Line 3: ...

you can see reading line example here – Line reading

You could use fileinput:

import os
import fileinput

for line in fileinput.input(os.listdir('.')):
    print(line)
Answered By: Peter Wood

You’re reading all the lines from the file, but you’re not outputting them. If you want to print the lines to standard output, you need to use print() as you did in your first example.

You can also write this somewhat more elegantly using contexts and more iterators:

from pathlib import Path 

file = Path('test.txt')
with file.open() as open_file:
    for line in open_file:
        print(line, end="")

test.txt:

Spam
Spam
Spam
Wonderful
Spam!
Spamity
Spam

Result:

Spam
Spam
Spam
Wonderful
Spam!
Spamity
Spam

Using a context for opening the file (with file.open()) means you inherently set up closing the file, and the iterator for the lines (for line in open_file) means you’re not loading the whole file at once (an important consideration with larger files).

Setting end="" in print() is optional depending on how your source files are structured, as you might otherwise end up printing extra blank lines in your output.

Answered By: Da Chucky
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.