2016-01-06 85 views
-2

我試圖讀取名爲testfile.txt的文本文件。 我使用NumPy函數genfromtext,但是我得到一個Index error: Too many indices在Python中讀取txt文件

文本文件包含數字的6列:

% Notes: 1A 
% Mach Number: 
% Barometric Pressure: 1036 bar 
% Load using MATLAB command: data = load('filename') 
% Columns: mm, p/pt, C4, C5, C4raw, C5raw 
    44.800000   0.781381  804.605260  1029.721933   -0.015945   -0.001723 
    56.800000   0.681254  699.772376  1027.182448   -0.022291   -0.001977 
    59.800000   0.627379  643.578986  1025.821491   -0.025692   -0.002113 
    62.800000   0.572096  586.082966  1024.447808   -0.029170   -0.002250 
    74.800000   0.440294  449.643875  1021.234840   -0.037422   -0.002571 
    79.800000   0.384134  391.777963  1019.900507   -0.040921   -0.002705 
    84.800000   0.336203  342.518031  1018.784082   -0.043898   -0.002816 
    96.800000   0.270190  274.847768  1017.238791   -0.047987   -0.002971 

這是我的代碼:

import numpy as np 
table = np.genfromtxt("testfile.txt",dtype = "float",delimiter = ",",comments = "%") 

mm = table[:,0] 
ppt = table[:,1] 
C4 = table[:,2] 
C5 = table[:,3] 
C4raw = table[:,4] 
C5raw = table[:,5] 

print ppt 
+2

更多信息:輸入文件(或它的一部分)和完整的錯誤 –

+1

上,則該錯誤發生什麼行代碼的? –

+0

錯誤發生在行mm = table [:,0]處,文本文件由六列數字組成。我添加了文本文件的圖像 – aeengineer

回答

1

由於對genfromtxt默認是使用(可能是多個)空格作爲分隔符,你可以有什麼你只需要:

table = numpy.genfromtxt('testfile.txt', comments="%") 

# etc. 

docs

默認情況下,假定genfromtxt delimiter=None,這意味着該線沿白色空間(包括翼片),並且連續的空格被認爲是一個單一的空白空間分開。

1

您的文件不是逗號分隔的。試試這個:

table = np.genfromtxt("test1.txt", dtype="float", comments="%")

與您提供的例子,這將返回正確的值給我。

+0

在這種情況下'評論'確實比'skip_header'更好的參數:o) – heltonbiker

+0

我設法讓它工作: 表= np.genfromtxt(「testfile.txt」,dtype =「float」,delimiter =「」,comments =「%」) mm = table [:,0] ppt = table [:,1] C4 =表[:,2] C5 =表[:,3] C4raw =表[:,4] C5raw =表[:,5] 打印毫米 – aeengineer

+0

@aeengineer你看到那些'\ t' ?您的文件不是逗號分隔的,它是製表符分隔的。在我上面的答案中使用第二行,這應該工作。 –

0

好的,經過一些試驗和錯誤,我現在解決了這個問題。 感謝您的幫助,省略了分隔符確實是heltonbiker所提出的最終解決方案。 這是我的代碼:需要

#Read the textfile "testfile.txt" and place all columns in a separate array 
table = np.genfromtxt("testfile.txt", comments="%") 

mm = table[:,0] 
ppt = table[:,1] 
C4 = table[:,2] 
C5 = table[:,3] 
C4raw = table[:,4] 
C5raw = table[:,5]