简体   繁体   English

如何使用python从.txt文件中提取两列?

[英]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. 我想从数据中提取两列,并使用python将它们保存在另一个文件中。

This is what I've done so far: I saved the file as .txt and then wrote this script: 到目前为止,这是我所做的:我将文件另存为.txt,然后编写了此脚本:

# -*- 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 . 问题是当我运行脚本时:我收到此错误: 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 这是不需要使用csv模块的解决方案

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

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

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