user1002288
user1002288

Reputation: 5040

python read/write a file list of files

In python 2.7, I need to perform the same operations for a list of file list.

Example, # each file is a file descriptor for example, fileX = open("someString", "a")

 fileList1 = [file1, file2, file3,file4,file5] 
 fileList2 = [file11, file21, file31,file41,file51] 
 allFilelist = [fileList1, fileList2]

When I try to read/write some strings on them I get:

 line = item.readline()
 IOError: [Errno 9] Bad file descriptor

 # each file in allFilList is a file list 
 allFilList = [ifcxRpsFileNameL, ircxRpsFileNameL, transXRpsFileNameL, ifcxFileNameL, 
 ircxFileNameL, transXFileNameL]
 for eachFileList in allFilList :
    for item in eachFileList :
            #print item.read 
            line = item.readline()
            #for line in :
            print "the line read from ", item, " is " , line
            ll= line.strip("\n").split()
            if len(ll) == 0 :
                print "the file " , item , " is empty \n"
                exit  
            elif len(ll) != TOTAL_ITR :
                print "the len of the file " , item , " is not " , TOTAL_ITR , "\n"
                exit
            else:
                item.write("\n")
                lt = [float(num) for num in ll]
                item.write(min(lt))
                item.write(" ") 
                item.write(sum(lt)/len(lt))
                item.write(" ")
                item.write(max(lt))
                item.write(" ")
                item.write("\n")
                item.close()
                break

In response to this comment:

print out item before you try to read from it and post the output

the output is: <open file 'ND_ifxc_2010_RPS.dat', mode 'a' at 0x2ba38d1e9558>

Upvotes: 0

Views: 638

Answers (1)

inspectorG4dget
inspectorG4dget

Reputation: 113945

The problem that you have comes from the fact that the files you have open are opened with mode 'a', and therefore, not for reading. As a result, attempting to read from a file not open for reading gives you an error.

You are likely better off storing a list of filepaths, and doing this:

  1. open with 'r' mode
  2. read lines
  3. based on your conditions, close them, reopen in 'a' mode and write the required lines.

Hope this helps

Upvotes: 3

Related Questions