立即写入文件或逐行附加 - 磁盘写入
我担心光盘驱动生活,我想知道哪种方式需要最少的写入,因此HDD/SSD不会太早磨损:
with open('file.txt', 'w') as f:
for line in lines:
f.write(line + '\n')
或者
with open('file.txt', 'w') as f:
f.write('\n'.join(lines))
f.write('\n') # just to keep the same content as in the previous example
我知道HDD驱动程序具有潮红机制,因此从理论上讲,两者都应该同样将驱动器戴出,但是我想通过询问来验证我的理解。
I'm concerned about disc drive life and I'd like to know which way takes minimum amount of writes, so the HDD/SSD won't wear out too soon:
with open('file.txt', 'w') as f:
for line in lines:
f.write(line + '\n')
or
with open('file.txt', 'w') as f:
f.write('\n'.join(lines))
f.write('\n') # just to keep the same content as in the previous example
I know HDD drivers have a flushing mechanism, so in theory, both should equally wear the drive out, but I'd like to verify my understanding by asking.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
无论您是否要执行一些预防措施,只要计算机中安装了其他程序,总会有读/写操作正在进行,并且此操作可以留下内存泄漏,因此没有办法假设您可以防止硬盘驱动器或SSD磨损。
尽管您更担心应用程序不对HDD/SSD造成任何损害,则可以保持健康的读/写操作。通常,这种操作包括确保在进行任何操作后释放或关闭任何读取资源。避免将大数据写入内存,要么将其分解为内存允许的最大限制或HDD/SSD读/写周期,还可以避免在文件上执行重复操作的冗余代码,例如在循环构造中运行的IO操作喜欢, while 和其他,如果您必须在循环中具有这种读/写操作,请延迟一些,并确保完成读取操作已完成和关闭或关闭或关闭或所有阅读或写作完成后释放。
Whether you want to enforce some precautionary actions or not, as long as there's other programs installed in your computer, there's always going to be read/write operation going on and this operation can either leave behind memory leak or not, so there's no way to say you can prevent the hard-drive or SSD from wearing out.
Although if you're more concern about your applications not doing any damage to the HDD/SSD, you can maintain a healthy read/write operation. Usually this kind of operation include making sure any read/write resource is freed or close after any operation is carried out. Avoid writing large data at once into memory, either break it down to the maximum limit allowed by your memory or HDD/SSD read/write cycle and also avoid redundant code that perform repetitive actions on a file such as IO operations running in a looping construct like
for
,while
and others and if you must have this kind of read/write operation on a loop, have some delay, and ensure the read operation is done and closed or freed after all the reading or writing is complete.