我正在用Python编写一个程序,试图从同一目录中读取两个不同的文件。我的代码如下所示:
for i in spectra_files:
with open(i, 'r') as f:
numbers = [] #list to store all mass spectrum data directly from file before being processed
for line in f:
if line[0].isdigit(): #skips header in file
numbers.append(line)
str_data = ''.join(numbers)
#creates list for the mass and list for the intensity. to be used for plotting
spectrum_mass = [int(x.split(',')[0].strip()) for x in str_data.split()]
spectrum_intensity = [int(x.split(',')[1].strip()) for x in str_data.split()]
spectrum_mass.append('||')
spectrum_intensity.append('||')
spectra_files = spectra_files[spectra_files.index(i)+1:]
目前我循环浏览文件名列表,然后将其数据添加到列表spectrum_mass和spectrum_intensity中。但是这不起作用,它只添加列表中最后一个文件的数据。有什么建议吗?
答案 0 :(得分:1)
几点说明:
spectra_files
列表(spectra_files = spectra_files[spectra_files.index(i)+1:]
)
spectrum_mass = []
spectrum_intensity = []
for i in spectra_files:
with open(i, 'r') as f:
numbers = [] #list to store all mass spectrum data directly from file before being processed
for line in f:
if line[0].isdigit(): #skips header in file
numbers.append(line)
str_data = ''.join(numbers)
#creates list for the mass and list for the intensity. to be used for plotting
spectrum_mass.extend(int(x.split(',')[0].strip()) for x in str_data.split())
spectrum_intensity.extend(int(x.split(',')[1].strip()) for x in str_data.split())
spectrum_mass.append('||')
spectrum_intensity.append('||')
答案 1 :(得分:0)
在循环外创建列表。对于每次迭代,列表都要重写。还有一个建议; 当你提问时;请跳过不相关的代码,你正在做什么与文件中的行做一个最小的虚拟代码。这使得关注和回答变得更加容易。
在您的代码中,您仍然没有同时“读取”2个文件。您正在循环读取一个文件,并同时在“2个列表”中“写入”。
我希望它有所帮助