Home > other >  Writing every two items in a list to a text file, then creating a new line
Writing every two items in a list to a text file, then creating a new line

Time:12-07

Full script essentially opens a txt file with three columns separated by a whitespace and saves it to a list words

with open(filename) as f:
    words = f.read().split()

Every third item is deleted from the list starting from position 2 using: del words[2::3]

The next step I would like to add is writing to the same filename with two of the three columns (or every two items in words), space them out and then create a new line in a text file:

('list_item1' ' ' 'list_item2' '/n'), ('list_item3' ' ' 'list_item4' '/n'), etc

Any help would be appreciated!

I've thus far only been able to split text from the text file into a list but would like to take every two items from that list and write to text file using the format: ('list_item1/3/5etc' ' ' 'list_item2/4/6etc' '/n')

with open(r'filename', 'w') as fp:
    fp.write(" ".join(str(item) for item in words))

CodePudding user response:

You can create an iterator for the list, and use the next function inside the loop to get the next element from the iterator.

my_lst = ["a", "b", "c", "d", "e", "f", "g", "h"]
list_iter = iter(my_lst)
with open(file_name, "w") as fp:
    for item in list_iter:
        try:
            item2 = next(list_iter)
        except StopIteration:
            fp.write(f"{item}\n")
        else:
            fp.write(f"{item} {item2}\n")

Which writes a file with:

a b
c d
e f
g h

The item2 line is wrapped in a try..except to catch the StopIteration that is thrown if the list iterator has been exhausted. In this case, only the first item is written to the file. If no StopIteration is thrown, the else block is executed, which writes both items and a newline to the file


A more general implementation of this would be to use a function that gives chunks of the desired size from your original list:

def chunks(collection, chunk_size):
    l = [] # An empty list to hold the current chunk
    for item in collection:
        l.append(item) # Append item to the current chunk
        if len(l) == chunk_size:
            yield l    # If chunk is of required size, yield it
            l = []     # Set current chunk to new empty list

    # Yield the chunk containing any remaining items
    if l: 
        yield l 

See What does the "yield" keyword do? for more information on what yield does.

Iterating over this function yields lists of chunk_size elements. We can just take these lists, join them with a space, and write them to the file:

with open(file_name, "w") as fp:
    for chunk in chunks(my_lst, 2):
        fp.write(" ".join(chunk))
        fp.write("\n")

Or, in a single line (ugh)

with open(file_name, "w") as fp:
    fp.write("\n".join(" ".join(chunk) for chunk in chunks(my_lst, 2)))
  • Related