0

我是 python 编程的新手,并且正在尝试创建一个使用 python 中的一段代码处理数千个文件的设置。我创建了一个练习文件夹来执行此操作。其中有两个 FITS 文件(FITS1.fits 和 FITS2.fits)。我做了以下操作将它们都放在一个 .txt 文件中:

ls > practice.txt

这是我接下来所做的:

$ python
import numpy
import pyfits
import matplotlib.pyplot as plt
from matplotlib import pylab
from pylab import *
import asciidata

a = asciidata.open('practice.txt')

print a[0][0] #To test to see if practice.txt really contains my FITS files FITS1.fits
i = 0
while i <=1 #Now I attempt a while loop to read data from columns in FITS files, plot the numbers desired, save and show the figures. I chose i <=1 because there are only two FITS files in the text(also because of zero-indexing). 

    b = pyfits.getdata(a[0][i]) # "i" will be the index used to use a different file when the while loop gets to the end

    time = b['TIME'] #'TIME' is a column in the FITS file
    brightness = b['SAP_FLUX']
    plt.plot(time, brightness)
    xlabel('Time(days)')
    ylabel('Brightness (e-/s)')
    title(a[0][i])

    pylab.savefig('a[0][i].png') #Here am I lost on how to get the while loop to name the saved figure something different every time. It takes the 'a[0][i].png' as a string and not as the index I am trying to make it be.

    pylab.show()

    i=i+1 # I placed this here, hoping that when the while loop gets to this point, it would start over again with a different "i" value

按两次回车后,我按预期看到了第一个数字。然后我将关闭它并查看第二个。但是,仅保存第一个图形。有没有人对我如何改变我的循环来做我需要的事情有任何建议?

4

2 回答 2

2

您应该使用 glob 自动获取适合文件作为列表,从那里使用 for 循环将让您直接迭代文件的名称,而不是使用索引。调用plt.savefig时,需要构造要保存的文件名。这是清理并放在一起的代码:

from glob import glob
import pyfits
from matplotlib import pyplot as plt

files = glob('*.fits')

for file_name in files:
    data = pyfits.getdata(file_name)
    name = file_name[:-len('.fits')] # Remove .fits from the file name

    time       = data['TIME']
    brightness = data['SAP_FLUX']

    plt.plot(time, brightness)

    plt.xlabel('Time(days)')
    plt.ylabel('Brightness (e-/s)')
    plt.title(name)

    plt.savefig(name + '.png')
    plt.show()
于 2012-06-18T20:51:55.750 回答
2

在您的代码中, i 被视为字母 i,而不是变量。如果您想保留此命名,您可以执行以下操作:

FileName = 'a[0][%s].png' % i
pylab.savefig(FileName)
于 2012-06-18T20:52:20.123 回答