Python:在不创建锁的情况下打开文件 [英] Python: Opening a file without creating a lock

查看:128
本文介绍了Python:在不创建锁的情况下打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python创建脚本来备份一些文件.但是,这些文件可以随时重命名或删除.我不希望我的脚本通过锁定文件来防止这种情况.在备份过程中,该文件应该仍然可以随时删除.

I'm trying to create a script in Python to back up some files. But, these files could be renamed or deleted at any time. I don't want my script to prevent that by locking the file; the file should be able to still be deleted at any time during the backup.

如何在Python中执行此操作?而且,会发生什么?如果无法读取流,我的对象会变成空吗?

How can I do this in Python? And, what happens? Do my objects just become null if the stream cannot be read?

谢谢!我对Python有点陌生.

Thank you! I'm somewhat new to Python.

推荐答案

如kindall所述,这是Windows特定的问题. Unix操作系统允许删除.

As mentioned by kindall, this is a Windows-specific issue. Unix OSes allow deleting.

要在Windows中执行此操作,我需要使用win32file.CreateFile来使用Windows特定的dwSharingMode标志(在Python的win32file中,它仅称为"sharingmode").这里是一些文档: http://docs.activestate.com/activepython/2.7/pywin32/win32file__CreateFile_meth.html

To do this in Windows, I needed to use win32file.CreateFile to use the Windows specific dwSharingMode flag (in Python's win32file, it's just called "sharingmode"). Here's some docs on it: http://docs.activestate.com/activepython/2.7/pywin32/win32file__CreateFile_meth.html

一个粗略的例子:

import win32file # Ensure you import the module.

file_handle = win32file.CreateFile('filename.txt', win32file.GENERIC_READ, win32file.FILE_SHARE_DELETE | win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, None, win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_NORMAL, None)

这篇关于Python:在不创建锁的情况下打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆