简体   繁体   中英

how to merge two columns into one (using Python)?

I need to merge two columns (first and second) into one column, using Python. Here is my file:

   0 C   -0.053959    0.000000         
   1 C   -0.053862    0.000000         
   2 C   -0.059245    0.000000         
   3 C   -0.058925    0.000000         
   4 S    0.050616    0.000000         
   5 H    0.040353    0.000000         
   6 H    0.040480    0.000000         
   7 H    0.045907    0.000000         
   8 H    0.045941    0.000000 

I already managed to reach my goal with Bash:

awk '{print $2 "" $1 "\ t" $3}' <MYfile.txt >> OUTPUT.txt

The result is :

C0      -0.053959
C1      -0.053862
C2      -0.059245
C3      -0.058925
S4      0.050616
H5      0.040353
H6      0.040480
H7      0.045907
H8      0.045941

Is it possible with Python ???

Use following code:

f=open('f.txt','r') #input file . change file name to your file name
f1=open('o.txt','w')  # output file 
d=f.readlines()
for i in d:
    k=i.strip().split()
    f1.write((k[1]+k[0]+' '+k[2]+"\n"))
f.close()
f1.close()

You can easily use split to convert each line into a list

with open("fileToRead.txt", "r") as fi, open("fileToWrite.txt", "w") as fo:
    for line in fi:
        x = line.strip().split()
        fo.write("{}{}\t{}\n".format(x[1], x[0], x[2]))

You can do something like this: I suppose that your input file is called test_file.txt and your output file is called new_file.txt :

def read_file(name):
    data = None
    with open(name, 'r') as f:
        data = f.readlines()
    return (k.split() for k in data) if data else data

def merge_columns(name, new_file):
    data = read_file(name)
    if not data:
        raise Exception('Cant operate with a None data')
    with open(new_file, 'a+') as f:
        for k in data:
            first, second, third, *_ = k
            f.write('{0}{1} {2}\n'.format(second, first, third))


merge_columns('test_file.txt', 'new_file.txt')

In terminal:

>>> python3 test.py
>>> cat new_file.txt
C0 -0.053959
C1 -0.053862
C2 -0.059245
C3 -0.058925
S4 0.050616
H5 0.040353
H6 0.040480
H7 0.045907
H8 0.045941

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