Hi all,
I would like to make program reading 300 lines form a file with 24 columns.
the 24th column has an integer from 1 to 24, while the others columns are strings.

I want to summarize in seperate files this (last) column

For example,
assdsd, sdsds, asdasda, asda ,asdad, asdsad, ...., 1
hfghhghghghg,ghgh,gh,gh,g,hg,hg,h,gh,g,hg,hg, ... ,2
rtrtrtr ,rt r,t r, t,r,t r,t ,r t,r ,t ,r , r,t r,.... ,1

File1.txt
assdsd, sdsds, asdasda, asda ,asdad, asdsad, ...., 1
rtrtrtr ,rt r,t r, t,r,t r,t ,r t,r ,t ,r , r,t r,.... ,1

File2.txt
hfghhghghghg,ghgh,gh,gh,g,hg,hg,h,gh,g,hg,hg, ... ,2

Could you help me do it please ??

Dani AI

Generated

A quick, practical way to do this in Python is to read each input line as raw text, split off the last comma (so the original spacing/quoting is preserved), parse the trailing field as an integer 1–24, then write the whole original line into the corresponding output file (File1.txt, File2.txt, ...). This avoids repeatedly opening/closing files and is simple to reason about. 's C joke writes and runs a Perl script via an external system call; if you prefer not to use Perl, the Python approach below does the same job directly. Also, as reminded the OP, post your attempt or any error messages if you get stuck.

# split_last_column.py
def split_by_last_field(inpath, out_prefix='File', out_ext='.txt', max_index=24):
    handles = {}
    try:
        with open(inpath, 'r', encoding='utf-8') as inf:
            for raw in inf:
                line = raw.rstrip('\r\n')
                if not line:
                    continue
                parts = line.rsplit(',', 1)          # split only on last comma
                if len(parts) != 2:
                    continue                         # malformed line
                last = parts[1].strip()
                try:
                    idx = int(last)
                except ValueError:
                    continue
                if not (1 <= idx <= max_index):
                    continue
                if idx not in handles:
                    fname = "{}{}{}".format(out_prefix, idx, out_ext)
                    handles[idx] = open(fname, 'w', encoding='utf-8')
                handles[idx].write(line + '\n')
    finally:
        for f in handles.values():
            f.close()

if __name__ == '__main__':
    split_by_last_field('input.txt')

Notes and troubleshooting tips: use this rsplit method when the last field is a plain integer and you want to keep each input line exactly as it appears. If your file contains quoted fields with embedded commas, use Python's csv module to parse rows (but be aware csv.reader may change spacing/quoting when you reserialize). Choose 'w' to overwrite existing FileN.txt or 'a' to append. If something goes wrong, post the exact input line(s) and any traceback so others can reproduce and suggest fixes.

Recommended Answers

All 4 Replies

Easiest C version, guaranteed. Probably won't work under Windows though.

#include <stdio.h>
#include <stdlib.h>

char const * const lines[] = {
    "my %files;\n",
    "while(<>) {\n",
    "   my($index) = /(\\d+)$/;\n",
    "   $files{$index} .= $_;\n",
    "}\n",
    "for(keys %files) {\n",
    "   open OUTPUT, '>', \"File$_.txt\";\n",
    "   print OUTPUT $files{$_};\n",
    "   close OUTPUT;\n",
    "}\n",
    0
};

int main(void)
{
    FILE *script;
    char const * const *p;
    script = fopen("summarize.pl", "w");
    for (p = lines; *p; p++) {
        fputs(*p, script);
    }
    fclose(script);
    return system("perl summarize.pl");
}
commented: nice one ))) +2

Besides the joke above, the rules of this forum require to give evidence of trying to solve the problem yourself. So go ahead and post your code and errors you are encountering.

Thanks for your answer but How can I run this ?
And what is the meaning of command

return system("perl summarize.pl");

It runs the Perl language program writen to file by the C program if you have Perl installed.

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.