G. Trialonis
G. Trialonis

Reputation: 99

to import txt file of words and print words in separate lines

I have a text file which contains 40 words, e.g. one two three ... forty. All words are below one another, no commas included. I need to print them to screen or to another file one next to each other, separated with commas, (e.g.: one, two, three, ...) and also have them wrap up every ten (10), or seven (7) words. This is my code, which fails to work:

import textwrap
flag = 1
comma = ', '

with open('drop_words.txt', encoding='utf-8') as file:
    content = file.read()
    content = content.split()
    words = comma.join(content)
    if len(content)%7 == 0:
        print(words, '\n')

Can anyone help? Thank you.

Upvotes: 1

Views: 117

Answers (2)

DirtyBit
DirtyBit

Reputation: 16772

drop_words.txt:

one
two
three
four

and then:

with open('drop_words.txt', encoding='utf-8') as file:
    content = file.readlines()
    # you may also want to remove empty lines
    content = [l.strip() for l in content if l.strip()]
    print(", ".join(content), end = '')

OUTPUT:

one, two, three, four

EDIT:

and if by wrapping the words together you mean grouping them, you could use a grouper like:

import itertools as IT

def grouper(n, iterable):
    iterable = iter(iterable)
    return iter(lambda: list(IT.islice(iterable, n)), [])

with open('list.txt', encoding='utf-8') as file:
    content = file.readlines()
    content = [l.strip() for l in content if l.strip()]
    print(", ".join(content))
    grouping = ", ".join(content)
    #creating a list out of the comma separated string
    grouping = grouping.split(",")
    # grouping the two elements
    print(list(grouper(2, list(grouping))))

OUTPUT:

one, two, three, four
[['one', ' two'], [' three', ' four']]

EDIT 2:

OP mentioned the pack of 10 digits in a row

wrap = 0
newLine = True
with open('list.txt', encoding='utf-8') as file:
    content = file.readlines()
    # you may also want to remove empty lines
    content = [l.strip() for l in content if l.strip()]
    for line in content:
        if wrap < 10:
            print("{}, " .format(line), end = '')
        else:
            if newLine:
                print("\n")
                newLine = not newLine
            print("{}, ".format(line), end='')
        wrap += 1

OUTPUT:

one, two, three, four, five, six, seven, eight, nine, ten, 

eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, 

Upvotes: 1

Jule
Jule

Reputation: 274

this might do the job for printing the names:

with open('drop_words.txt', encoding='utf-8') as f:
    words = [line for line.strip() in f]
    print(','.join(words))

If you want to wrap them by pack of 7 words, you can use a function as following:

def grouped(iterable, n):
    return zip(*[iter(iterable)]*n)

>>> grouped(word, 7)

Upvotes: 0

Related Questions