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()
CodePudding user response:
You could use fileinput
:
import os
import fileinput
for line in fileinput.input(os.listdir('.')):
print(line)
CodePudding user response:
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.
CodePudding user response:
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