How can we in python change the number of elements in a line to the next, this is, for example...

We have the following txt file:

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

And we want a program which the output is:

1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16

So how can I obtain an output file with only 3 columns instead of 4 like the original file???

Dani AI

Generated

The input is just a stream of tokens (numbers or words). Treat the file as a sequence and re-chunk it into lines of the desired width. That answers the “how” implied by — explain the transformation in plain steps — and implements the container idea mentioned: keep a small buffer and flush it when it reaches the new column count.

A simple, memory-friendly approach that works for most files:

def rewrap_file(inpath, outpath, m=3):
    with open(inpath, 'r', encoding='utf-8') as f:
        tokens = f.read().split()
    with open(outpath, 'w', encoding='utf-8') as out:
        for i in range(0, len(tokens), m):
            out.write(' '.join(tokens[i:i+m]) + '\n')

For very large files avoid reading everything at once. Stream tokens and flush the buffer as soon as it reaches m:

def rewrap_stream(inpath, outpath, m=3):
    buf = []
    with open(inpath, 'r', encoding='utf-8') as f, open(outpath, 'w', encoding='utf-8') as out:
        for line in f:
            for tok in line.split():
                buf.append(tok)
                if len(buf) == m:
                    out.write(' '.join(buf) + '\n')
                    buf.clear()
        if buf:
            out.write(' '.join(buf) + '\n')

Notes and troubleshooting: str.split() handles arbitrary whitespace. If the file uses commas or another delimiter, replace them or use the csv module. Quoted fields, embedded commas, or fixed-width columns require a different parser. If you need to preserve original spacing or comments, parse carefully instead of tokenizing blindly. This implements the English-algorithm idea from and the small-container tactic from while addressing large-file concerns mentioned implicitly by the problem posted by .

Recommended Answers

All 2 Replies

Well, start with a thought. How can you explain the process to someone else in English? Make it general: given data in rows of n, how would you rewrite it in rows of m?

Once you have that explanation in English, it will lead to the thought that gives the code.

Jeff

Start with some code to read the file, as well as the file you want to write to. Also, how large is the input file? Hint, you will want probably want to use some kind of a container to hold the 3 items you want to write.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.