1

I wrote a simple python script to automatically detect a file added in the directory, and then I would do sth to this new-added file. One issue I tried to solve is how to determine if the file copy process has completed.

1) how to detect a file added in the directory - solved

http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html

2) how to detect a file copy process completed?

One solution is to compare size as suggested in the following post. But I tried this method, I found it did not work. When the file was still copying (Win7 pop-up window still showed 13 mins left), the piece of code has indicated that file copy has completed.

Can anyone help check why it did not work? Is there any better way to detect file copy process completed?

Python - How to know if a file is completed when copying from an outside process

file_size = 0
while True:
    file_info = os.stat(file_path)
    if file_info.st_size == 0 or file_info.st_size > file_size:
        file_size = file_info.st_size
        sleep(1)
    else:
        break

I camp up the following solution by myself. Rather than checking file size, I tried to open this file. If IOError is seen, sleep 2 seconds and then retry.

Let me know if you have a better solution.

result = None
while result is None:
try:
    result = open(logPath)
except IOError:
    time.sleep(2)
result.close()
Community
  • 1
  • 1
Lazysheep.wang
  • 129
  • 1
  • 2
  • 12

0 Answers0