我想读取一个文件,但没有任何锁定。
with open(source, "rb") as infile:
data = infile.read()
Run Code Online (Sandbox Code Playgroud)
上面的代码可以锁定源文件吗?
该源文件可以随时使用新行进行更新(例如在我的脚本运行期间)。我认为不是,因为它仅处于阅读模式(“rb”)。但我发现我们可以使用Windows API来无锁地读取它。我没有找到我的问题的简单答案。
我的脚本在本地运行,但源文件和在其上附加更改的脚本/软件不是(网络驱动器)。
打开文件不会对其加锁。事实上,如果您需要确保单独的进程不会同时访问文件,所有这些进程都必须协同采取特殊步骤,以确保一次只有一个进程访问该文件(请参阅在 Python 中锁定文件) 。这也可以通过以下小程序来证明,该程序故意花时间读取文件,以便让另一个进程(即我使用文本编辑器)有机会在程序运行时将一些数据附加到文件末尾。该程序一次读取并输出一个字节,每次读取之间暂停 0.1 秒。在程序运行期间,我在文件末尾添加了一些附加文本,并且程序打印了附加文本:
import time
with open('test.txt', "rb") as infile:
while True:
data = infile.read(1)
if data == b'':
break
time.sleep(.1)
print(data.decode('ascii'), end='', flush=True)
Run Code Online (Sandbox Code Playgroud)
如果您需要一个单字节字符串,您可以分段读取文件,然后将这些片段连接在一起。但这不会像单次读取文件那样节省内存:
BLOCKSIZE = 64*1024 # or some other value depending on the file size
with open(source, "rb") as infile:
blocks = []
while True:
data = infile.read(BLOCKSIZE)
if data == b'':
break
blocks.append(data)
# if you need the data in one piece (otherwise the pieces are in blocks):
data = b''.join(blocks)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2090 次 |
| 最近记录: |