简体   繁体   中英

printing specific cols in python txt file

I'm trying to read in my data stored in a text file containing 25 columns split up by, eg

erd,thr,yui

I want to select the 4th and 13th columns and write them to a text file , side by side eg

Mark , baseball

I have researched and found code which can do this for a single column but i cant get it working for two , does anyone know how to do this ?

Heres the code I was trying to use

col = 2 # third column
filename = '4columns.txt'
third_column = [line[:-1].split('\t')[col] for line in open(filename,
'r')]

Python has a "csv" module (comma-separated values) which you can use for something like this.

import csv

with open( "myfile.txt", "r" ) as f:
    for row in csv.reader( f ):
        print row[3], ",", row[13]

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