在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>
答案 0 :(得分:3)
您遇到的问题来自于您打开的文件是以模式'a'
打开的,因此不是为了阅读。因此,尝试从未打开的文件中读取会导致错误。
最好存储一个文件路径列表,并执行以下操作:
'r'
模式'a'
模式重新打开并写下所需的行。希望这有帮助