I am needing to write a code that prints 5 words per line from a text file. I have figured out how to print each line individually on a new line but can't figure out the loop to get it to 5 words per line.
def justify(filename):
with open(filename, 'r') as file:
for line in file:
for word in line.split():
print(word)
Example of input: This is a test file example. This is just for show. File for testing code.
Example of output:
This is a test file
example. This is just for
show. File for testing code.
CodePudding user response:
If you want to print all the words in the file, with five on each output line, the following code should work:
def justify(filename):
with open(filename, 'r') as file:
somewords = []
for line in file:
for word in line.split():
somewords.append(word)
if len(somewords) == 5:
print(*somewords)
somewords.clear()
if somewords: # any words left unprinted
print(*somewords)
CodePudding user response:
To fix your code, you could add a word counter using enumerate
and only print the word if it is in the first 5:
def justify(filename):
with open(filename, 'r') as file:
for line in file:
for i, word in enumerate(line.split()):
if i < 5:
print(word, end=' ')
else:
break
print()
Or you could wrap that loop up as a generator expression and join it with a space:
def justify(filename):
with open(filename, 'r') as file:
for line in file:
print(' '.join(word for i, word in enumerate(line.split()) if i < 5))