简体   繁体   English

读取文本文件中特定列和行中的数据

[英]read data in specific column and row of a text file

I Have a text file which contain 3 columns and 20000 rows. 我有一个包含3列和20000行的文本文件。 I like to know what should I do to get the specific data (for example) in row 1000 and column 2? 我想知道如何获取第1000行和第2列中的特定数据(例如)? My first column is formatted like AAAA and my second column is a number like 1234. I tried this solution but I got an error based on my first column being letters I would like to define a variable which contains my data at the end: 我的第一列的格式类似于AAAA,第二列的格式类似于1234。我尝试了此解决方案,但是由于第一列是字母,因此我想定义一个变量,该变量最后包含我的数据,因此出现错误:

with open ('my_file') as f:
    for x , line in eumerate(f):
         if x = 1000:
             numfloat = map(float , line.split())
             print numfloat[1]

You are trying to use float() on something that contains letters. 您试图在包含字母的东西上使用float() this happens when you call: 发生这种情况,当您致电:

numfloat = map(float , line.split()) 

You need to tell us the exact output that you are looking for but here is one possible solution 您需要告诉我们您想要的确切输出,但这是一种可能的解决方案

num_float = map(float, line.split()[1])

or better yet

num_float = float(line.split()[1])

This will only get you the middle column, I'm not certain if you need the entire row or not. 这只会为您提供中间的列,我不确定是否需要整个行。

Additionally, as noted below, you need to change = to == in your if statement. 此外,如下所述,您需要在if语句中将=更改为== = is for assigment, == is for comparison. =表示比较, ==表示比较。

make '=' to '==' at line 3 of your code 在代码的第3行将'='变为'=='

with open('my_file', 'r') as f:
    for x, line in enumerate(f):
        if x == 1000:
            print float(line.split()[1])
import re

with open('my_file', 'r') as f:
    for x, line in enumerate(f):
        if x == 1000: 
            array = re.split('(\d+)',line) # array=['AAAA','123'] if line='AAAA123'
            print array[1] # your required second row.

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

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