Class3中的Python3关闭文件句柄

时间:2018-03-28 09:52:09

标签: python-3.x class filehandle

我试图关闭类中的文件。但无论我尝试什么,它都会保持开放。所以我的问题很简单。

为什么不关闭?

非常欢迎任何帮助或解释。提前谢谢!

import os
class LoopFolders:
    def __init__(self, targetFolder):
        self.targetFolder = targetFolder
        print('Target Folder:', targetFolder)

    def closeFile(self):
        self.logFile.close()
        print('All done!')

    def loop(self):
        self.logFile = open('FileList.txt', 'w')
        for root, subs, files in os.walk(self.targetFolder):
            print('Root:', root)
            self.logFile.write('Root:\n'+root+'\n')
        self.closeFile()

        # This doesn't work either:
        # self.logFile.close()

# code run example
run = LoopFolders('c:/')
run.loop()

1 个答案:

答案 0 :(得分:0)

我通过将写入部分放在with函数下来解决了这个问题。 再次感谢您的帮助!

import os
class LoopFolders:
    def __init__(self, targetFolder):
        self.targetFolder = targetFolder
        print('Target Folder:', targetFolder)

    def loop(self):
        with open('fileList.txt', 'w') as self.logFile:
            for root, subs, files in os.walk(self.targetFolder):
                print('Root:', root)
                self.logFile.write('Root:\n')
                self.logFile.write(root+'\n')

                print('\tSubfolders:', subs)
                self.logFile.write('\tSubfolders:\n')
                for sub in subs:
                    self.logFile.write('\t'+sub+'\n')

                print('\t\tFiles:\n')
                self.logFile.write('\t\tFiles:\n')
                for file in files:
                    try:
                        print('\t\t', file, '\n')
                        self.logFile.write('\t\t'+file+'\n')
                    except:
                        print('File in', root, 'could not be read')
                        self.logFile.write('file in '+root+' could not be read')
                        continue
            self.logFile.write('\n\n')

run = LoopFolders('C:/').loop()