0

在 python 2.7 中,我需要对文件列表执行相同的操作。

例如,#每个文件都是一个文件描述符 例如,fileX = open("someString", "a")

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

当我尝试在它们上面读/写一些字符串时,我得到:

 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

针对此评论:

在您尝试读取项目并发布输出之前打印出项目

输出是:<open file 'ND_ifxc_2010_RPS.dat', mode 'a' at 0x2ba38d1e9558>

4

1 回答 1

3

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

于 2012-07-23T23:00:07.683 回答