如何将两列合并为一个(使用Python)?

时间:2017-12-09 14:39:05

标签: python arrays

我需要使用Python将两列(第一列和第二列)合并为一列。 这是我的档案:

   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 

我已经设法通过Bash实现了我的目标:

awk '{print $2 "" $1 "\ t" $3}' <MYfile.txt >> OUTPUT.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

是否可以使用Python ???

3 个答案:

答案 0 :(得分:1)

使用以下代码:

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()

答案 1 :(得分:1)

您可以轻松使用split将每行转换为列表

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]))

答案 2 :(得分:1)

您可以这样做: 我想您的输入文件名为test_file.txt,输出文件名为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')

在终端:

>>> 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