简体   繁体   中英

How can I extract two columns from a .txt file with python?

I have done some calculation. I want to extract two columns from the data and save them in another file with python.

This is what I've done so far: I saved the file as .txt and then wrote this script:

# -*- coding: utf-8 -*-

import csv

f = open('file.txt')

csv_f=csv.reader(f)

for row in csv_f:

     print row[1:3] # to get the second and third columns

f.close()

The problem is when I am running the script: I got this error: IndexError: list index out of range .

I already know what the problem is because it shows all results in each row as on character in the list. How ever I don't know how to solve this problem to get them separately in a row.

This is two first rows of the file as an example:

Ene:   1    -0.429787341139E+03   -0.42979E+03   -0.59461E+01  4296   0.664E+00    0.167E+01
Ene:  2    -0.395935688219E+03    0.33852E+02   -0.43868E+01  4356   0.711E+00    0.928E+00

but this is what I got when I use print row:

['Ene:   1    -0.429787341139E+03   -0.42979E+03   -0.59461E+01  4296   0.664E+00    0.167E+01']
['Ene:   2    -0.395935688219E+03    0.33852E+02   -0.43868E+01  4356   0.711E+00    0.928E+00']

I'd really appreciate any help with this problem.

您必须指定正确的定界符(默认为',' ):

csv_f = csv.reader(f, delimiter='\t')  # if the file is tab delimited

Here is a solution that doesn't require the use of the csv module

with open('test.txt', 'r') as data: #using the with keyword ensures files are closed properly
  for line in data.readlines():
    parts = line.split(',') #change this to whatever the deliminator is
    print parts[0], parts[1] # parts[0] is the first column and parts[1] is the second column
import csv

f = open('file.txt')

csv_f=csv.reader(f)

for row in csv_f:

     print row.split(" ").[1:3] # to get the second and third columns

f.close()

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