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

2024-09-28 19:23:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一些计算。我想从数据中提取两列,并用python将它们保存在另一个文件中。在

到目前为止,我所做的就是:将文件保存为.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()

问题是当我运行脚本时:我得到了这个错误:IndexError: list index out of range。在

我已经知道问题出在哪里了,因为它将每一行的所有结果显示为列表中的on字符。我怎么也不知道怎么解决这个问题,把它们分开排成一排。在

以文件的前两行为例:

^{pr2}$

但这是我使用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']

如果你能帮我解决这个问题,我会非常感激的。在


Tags: 文件csv数据importtxt脚本foropen
3条回答

这是一个不需要使用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()

必须指定正确的分隔符(默认值为','):

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

相关问题 更多 >