简体   繁体   中英

Arranging a multi-column text file into a 2-column format, VBA or Python

I have .dat files of UTM x,y coordinates but the x,y pairs are in rows along 5 columns. I am trying to get them into one simple x,y column.

From this:

10 11  12 13  14 15  16 17  18 19
20 21  22 23  24 25  26 27  28 29
30 31  32 33  34 35

To this:

10 11
12 13
14 15
16 17
18 19
20 21
22 23
24 25
26 27
28 29
30 31
32 33
34 35

A colleague had a VBA script working for this, but he forgot to save it after testing it, and now I'm on my own. I use Python and have very little VBA experience.

Looks like you can just break lines at the double spaces:

>>> data = '''10 11  12 13  14 15  16 17  18 19
20 21  22 23  24 25  26 27  28 29
30 31  32 33  34 35'''
>>> print(data.replace('  ', '\n'))
10 11
12 13
14 15
16 17
18 19
20 21
22 23
24 25
26 27
28 29
30 31
32 33
34 35

Or splitting values and then going through x,y pairs:

>>> data = '''10 11  12 13  14 15  16 17  18 19
20 21  22 23  24 25  26 27  28 29
30 31  32 33  34 35'''
>>> xy = data.split()
>>> for x, y in zip(xy[0::2], xy[1::2]):
    print(x, y)
10 11
12 13
14 15
16 17
18 19
20 21
22 23
24 25
26 27
28 29
30 31
32 33
34 35

This seems to work fine for me under Python 3.4.3:

with \
    open('C:/Users/Gord/Desktop/thing.dat', 'r') as fin, \
    open('C:/Users/Gord/Desktop/thing.txt', 'w') as fout:
    for line in fin:
        items = line.split()
        for i in range(0, len(items), 2):
            print(items[i] + ' ' + items[i+1], file=fout)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM