I have a group of files (A.txt, AA.txt etc) in the form

A.txt :
A,45,56,78,98,11,23
A,98,90,33,76,30,40

AA.txt :
AA,65,76,34,76,98,12
AA,12,76,33,76,33,89

How can I quickly remove the symbol column (A,AA) from all these files using Python?
(I want to use python because the number of txt files is 3200)

Thank you.

Recommended Answers

All 3 Replies

You can try something like this

#!/usr/bin/env python
# -*-coding: utf8-*-
# Title: remcol.py

# WARNING: UNTESTED

import os

class Error(Exception):
    pass

def remove_column(srcdir, dstdir = None):
    if dstdir is None:
        dstdir = os.path.join(os.path.expanduser("~"), "columnremoved")
    if os.path.exists(dstdir):
        # this guarantees that this function won't overwrite anything on the disk
        raise Error(("destination directory exists", dstdir))
    else:
        os.mkdir(dstdir)
    for filename in os.listdir(srcdir):
        if not filename.endswith(".txt"):
            continue
        inname = os.path.join(srcdir, filename)
        outname = os.path.join(dstdir, filename)
        with open(outname, "w") as ofh:
            with open(inname, "r") as ifh:
                for line in ifh:
                    line = line.split(",", 1)[1]
                    ofh.write(line)
    return dstdir

if __name__ == "__main__":
    dstdir = remove_column(r"/path/to/the/directory/containing/the/3200/files")
    print("output files written to directory '%s'" % dstdir)

Man that was awesome.Python is really quick!It processed all this files in about 5 seconds!I am stunned!By the way what books do you suggest so that I can learn python?
Thank you again for this exceptional script.

By the way what books do you suggest so that I can learn python?

I suggest to start with 'dive into python' (or into python 3 if you want to use python 3). Notice that a good part of proficiency in python programming comes from knowing existing libraries (especially the standard library). This can be acquired only by writing many scripts (and reading the python forum).

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.