-1

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.

Daniel2805
  • 77
  • 1
  • 8
  • What have you tried so far? – Nelewout Sep 19 '18 at 11:16
  • I tryed Vijay's solution. It does what I want. Now, I want to print it into a new file. I guess this works partly with Shakeel's part. But he misunderstoood me. Each column is a variable. And each column has a predefinded length. – Daniel2805 Sep 19 '18 at 11:24

2 Answers2

0

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

Vijay Lingam
  • 101
  • 4
0

If you are looking to separate each line(since each line has one variable) by some delimiter(,) then use this.

with open('input.txt', 'r') as input_f: with open('output.txt', 'w') as output_f: for line in input_f: line = line.rstrip('\n') + ',' print(line, file=output_f)

Shakeel
  • 1,869
  • 15
  • 23