python多线程文件备份
时间: 2023-08-29 10:12:24 浏览: 43
以下是一个简单的Python多线程文件备份程序示例:
```python
import os
import shutil
import threading
def backup(source, destination):
shutil.copy(source, destination)
if __name__ == '__main__':
source_dir = '/path/to/source/directory'
destination_dir = '/path/to/destination/directory'
num_threads = 4
# create destination directory if it does not exist
if not os.path.exists(destination_dir):
os.makedirs(destination_dir)
# get list of files to backup
files_to_backup = [os.path.join(source_dir, f) for f in os.listdir(source_dir) if os.path.isfile(os.path.join(source_dir, f))]
# calculate number of files per thread
files_per_thread = len(files_to_backup) // num_threads
# create threads for backup
threads = []
for i in range(num_threads):
start = i * files_per_thread
end = (i + 1) * files_per_thread if i < num_threads - 1 else len(files_to_backup)
thread = threading.Thread(target=backup, args=(files_to_backup[start:end], destination_dir))
thread.start()
threads.append(thread)
# wait for all threads to complete
for thread in threads:
thread.join()
print('Backup complete!')
```
这个程序将一个目录中的所有文件备份到另一个目录中。程序首先创建目标目录(如果不存在),然后获取要备份的文件列表。接下来,程序将文件列表分成多个线程,每个线程负责备份一部分文件。每个线程都调用`backup`函数,该函数将源文件复制到目标目录中。最后,程序等待所有线程完成后输出备份完成的消息。