简体   繁体   English

如何在python中从txt中选择不同的列

[英]how to select different columns from txt in python

I want to print out my first column with other columns(as tab seperated) respectively.我想分别用其他列(作为制表符分隔)打印出我的第一列。 For example Col1+Col2 for first print, Col1+Col3 for second Col1+Col4 so on.例如,Col1+Col2 用于第一次打印,Col1+Col3 用于第二次打印 Col1+Col4,依此类推。 However I printed out just Col1+Col2 with my code below.但是,我使用下面的代码仅打印出了 Col1+Col2。 Why for loop is not progressing?为什么 for 循环没有进展?

import csv
with open('/Users/elf/Desktop/TEST_DATA/text_haplo.txt', 'r', encoding="utf-8", errors="ignore") as text_haplo:
    next(text_haplo)
    for i in range(1, 5):
        for line in text_haplo:
            line = line.split('\t')
            print(line[0], line[i])

The input is:输入是:

A    1    2    3
B    10   20   30
C    100  200  300

And I want the output sth like:我想要输出……

A 1
B 10
C 100

A 2
B 20
C 200

A 3
B 30
C 300

Updated version:更新后的版本:

for i in range(1, 4):
    with open('test.csv') as f:
        for line in f:
            line = line.rstrip().split('\t')
            print(line[0], line[i])
        print()

However, it's not a good practice to read the file again and again.但是,一遍又一遍地读取文件并不是一个好习惯。 It is acceptable only if your target machine lacks the RAM or the file is extremely big.仅当您的目标机器缺少 RAM 或文件非常大时才可以接受。 Otherwise it's better to read it once to memory and then output it in desired order:否则最好将其读取一次到内存中,然后按所需顺序输出:

data = []
with open('test.csv') as f:
    for line in f: data.append(line.rstrip().split('\t'))

for i in range(1, 4):
    for columns in data:
        print(columns[0], columns[i])
    print()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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