Search code examples
python-3.xfile-processingtext-manipulation

Inserting comma at predetermined positions in txt file


I have a file that comes as follows:

10030004
10300048
10919013

That is a txt file which contains data and each new line is a new observation. This file comes along with a document stating that for instance:

Variable: A Start: 1 Length: 3

Variable: B Start: 4 Length: 2

Variable: C Start: 6 Length: 3

I want to include delimiter to distinguish the different variables. Moreover, I want to include a header. Let's suppose I want to use , as the delimiter. Does anyone know how to proceed?

Okay, for the sake of completeness:

inpath = 'test.txt'
outpath = 'output.txt'

head = "A,B,C"
Astart = 1
Alength = 3
Bstart = 4
Blength = 2
Cstart = 6
Clength = 3


with open(inpath, 'r') as input_f:
    with open(outpath, 'w') as output_f:
        print(head, file = output_f)
        for line in input_f:
            print(line[Astart-1:Astart-1+Alength]+','+line[Bstart-1:Bstart-1+Blength]+','+line[Cstart-1:Cstart-1+Clength], file = output_f)

Thanky to everyone who helped me so far.


Solution

  • Try slicing like below:

    a = '10030004'

    print a[Astart-1:Astart-1+Alength]+','+a[Bstart-1:Bstart-1+Blength]+','+a[Cstart-1:Cstart-1+Clength]

    Where as in your case:

    Astart = 1, Alength = 3, Bstart = 4, Blength = 2, Cstart = 6, Clength = 3