![](/img/trans.png)
[英]Python - BeautifulSoup - Scraped content only being written to first text file, not subsequent files
[英]Write a file to disk only when first content is written into it
我用打開文件:
mylog = open('test.log', 'w')
有時在我的應用程序運行期間一些內容會寫在mylog
中; 但有時在應用程序運行期間什么也不寫,這要視情況而定。
在這兩種情況下,似乎總是在磁盤上創建文件test.log
。
只有將第一個內容寫入磁盤后,才可以將文件寫入磁盤嗎? (例如,類似mylog.write('blah')
東西)
即,如果從未調用mylog.write('...')
,則不會在磁盤上創建(空)文件test.log
。
創建自己的文件包裝器類,存儲文件對象。 它需要以下方法才能與上下文管理器和正常關閉功能一起使用
class MyFile():
def __enter__(self):
return self
def __init__(self, path, *args):
''' store the path, but don't actually open the file '''
self.path = path
self.file_object = None
self.args = args
def write(self, s):
''' you open the file here, just before writing '''
if not self.file_object:
self.file_object = open(self.path, *self.args)
self.file_object.write(self, s)
def close(self):
''' close the file '''
if self.file_object:
self.file_object.close()
def __exit__(self, exc_type, exc_value, exc_traceback):
self.close()
您可以使用上下文管理器打開/關閉:
with MyFile('test.log', 'w') as mylog:
mylog.write('...')
或以經典方式直接調用函數:
mylog = MyFile('test.log', 'w')
mylog.write('...')
mylog.close()
您必須創建一個包裝對象,該對象僅在調用第一個write()
時才實際打開文件:
class DelayedFile(object):
fileobj = None
def __init__(self, filename, *args, **kw):
self.filename = filename
self.args = args
self.kw = kw
def write(self, data):
if self.fileobj is None:
self.fileobj = open(self.filename, *self.args, **self.kw)
return self.fileobj.write(data)
def close(self):
if self.fileobj is not None:
return self.close()
def __enter__(self):
return self
def __exit__(self, *args, **kw):
if self.fileobj is not None:
return self.fileobj.__exit__(*args, **kw)
注意,這有一些缺點。 在第一個write()
調用之前,不會引發任何打開時的I / O錯誤。
上面的代理對象僅實現標准file
對象API的子集; 您可以根據需要添加更多方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.