Syd
Syd

Reputation: 421

Read in two files from same directory

I am writing a program in Python that is trying to read in two different files from the same directory. My code looks like this:

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:]

Currently I have it looping through a list of the names of the files, and then adding their data to the lists spectrum_mass and spectrum_intensity. However this is not working and it is only adding the data from the last file in the list. Any suggestions?

Upvotes: 0

Views: 127

Answers (2)

Mandar
Mandar

Reputation: 1769

Create lists outside the loop. For each iteration the list is getting over written. And one more suggestion; When you ask question; please skip irrelevant code of what are you doing with the lines in the file do a minimal dummy code. It makes it much more easier to follow and answer.

In your code still you are not "Reading" in 2 files simultaneously. You are reading in a loop one file at a time and "Writing" in 2 lists simultaneously.

I hope it helps

Upvotes: 0

Ioan Alexandru Cucu
Ioan Alexandru Cucu

Reputation: 12269

A couple of notes:

  • extend lists you construct OUTSIDE of your loop.
  • you need to NOT change the list you iterate on while iterating it. I'm referring to the spectra_files list which you change at the end of your loop (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('||')

Upvotes: 1

Related Questions