社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何在python中一次读写同一个文件

user1720713 • 5 年前 • 1528 次点击  

有三个python程序,writer程序 (writer.py) 写入文件 output.txt (reader_1.py, reader_2.py) 从同一个 output.txt file 同时。

如果另一个程序正在写入输出文件,如何避免读取器程序读取? 如何在python中高效地处理单写器和多读器问题?

我试图实现fnctl锁定机制,但是在python中找不到这个模块。

作家.py

#!/usr/bin/python
import subprocess
import time

cycle = 10

cmd="ls -lrt"

def poll():
   with open("/home/output.txt", 'a') as fobj:
      fobj.seek(0)
      fobj.truncate()
      try:
          subprocess.Popen(cmd,  shell=True,  stdout=fobj)
      except Exception:
          print "Exception Occured"

# Poll the  Data
def do_poll():
    count = int(time.time())

    while True:

        looptime = int(time.time())

        if (looptime - count) >= cycle:
             count = int(time.time())
             print('Begin polling cycle')
             poll()
             print('End polling cycle')

def main():
    do_poll()

if __name__ == "__main__":
    main()

#!/usr/bin/python

with open("/home/output10.txt", 'r') as fobj:
   f=fobj.read()

print f

#!/usr/bin/python语言

以open(“/home/output10.txt”,'r')作为fobj:
f=fobj.read()

打印f

reader_1.py和reader_2.py在while循环中连续运行。 由于这个原因,同一个文件被三个程序同时访问。

寻找想法。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/55049
 
1528 次点击  
文章 [ 1 ]  |  最新文章 5 年前