2013-02-05 45 views
0

我需要将文本文件中的值读入数组Z.这可以很好地使用单个文件ChiTableSingle,但是当我尝试使用多个文件时失败。它似乎是正确读取行,并生成Z,但只给[z] [],然后我得到错误,设置一个序列的数组元素。读取多个文件和数组

这是我当前的代码:

rootdir='C:\users\documents\ChiGrid' 
fileNameTemplate = r'C:\users\documents\ContourPlots\Plot{0:02d}.png' 

for subdir,dirs,files in os.walk(rootdir): 
    for count, file in enumerate(files): 

     fh=open(os.path.join(subdir,file),'r') 
     #fh = open("ChiTableSingle.txt"); 

     print 'file is '+ str(file) 

     Z = [] 
     for line in fh.readlines(): 
      y = [value for value in line.split()] 
      Z.append(y) 

     print Z[0][0] 
     fh.close() 

     plt.figure() # Create a new figure window 

     Temp=open('TempValues.txt','r') 
     lineTemp=Temp.readlines() 
     for i in range(0, len(lineTemp)): 
      lineTemp[i]=[float(lineTemp[i])] 

     Grav=open('GravValues2.txt','r') 
     lineGrav=Grav.readlines() 
     for i in range(0, len(lineGrav)): 
      lineGrav[i]=[float(lineGrav[i])] 

     X,Y = np.meshgrid(lineTemp, lineGrav) # Create 2-D grid xlist,ylist values 

     plt.contour(X, Y, Z,[1,2,3], colors = 'k', linestyles = 'solid') 
     plt.savefig(fileNameTemplate.format(count), format='png') 
     plt.clf() 

回答

0

我注意到的第一件事情是,你的列表理解y = [value for ...]只会返回一个字符串列表(从split()功能),所以你要转换在试图绘制它们之前,它们在某个点上变成数字格式。另外,如果您正在阅读的文件只是以空格分隔的数字表格,则应考虑使用numpy.loadtxt(fh),因为它需要分割和类型转换,并返回一个2-d numpy.array。如果行以常规python注释字符开头(例如# this line is a comment and will be ignored),您也可以添加它将忽略的注释文本。

只是另一个想法,我会小心使用与python方法相同的变量名(例如,在这种情况下单词file)。一旦你将它重新定义为别的东西,以前的定义就不复存在了。

+0

对于使用y = [...]的单个文件它都可以正常工作,但是仍然需要先将其转换为浮点数或其他东西?我也尝试过np.loadtxt,但那是说没有属性readlines等。 – user1841859