【问题标题】:Python3 close file handle inside ClassPython3关闭类内的文件句柄
【发布时间】:2018-03-28 09:52:08
【问题描述】:

我正在尝试关闭类中的文件。但无论我尝试什么,它都保持打开状态。所以我的问题很简单。

为什么不关闭?

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

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()

【问题讨论】:

  • 你的班级怎么称呼,怎么不工作?
  • 此外,此代码将引发 SyntaxErro,因为您在 __init__ 之前省略了 def 关键字。
  • 类的初始化缺少“s”应该是run = LoopFolders()
  • 快速测试显示正在调用 close ,我在第一个循环后添加了一个 break 语句 5 Target Folder: c:/ Root: c:/ Root: c:/$Recycle.Bin Root: c:/$Recycle.Bin\S-1-5-21-147214757-305610072-1517763936-2309274 Root: c:/$WINDOWS.~BT Root: c:/$WINDOWS.~BT\Sources All done!

标签: python-3.x class filehandle


【解决方案1】:

我通过将写入部分放在 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多