使用python使用单独的线程重命名文件夹中的每个文件

使用python使用单独的线程重命名文件夹中的每个文件,python,multithreading,operating-system,python-multithreading,Python,Multithreading,Operating System,Python Multithreading,我正在努力学习python中的线程 到目前为止,这是我写的一个简单的小菜一碟: path = "/Users/userName/Desktop/temp/bluetooth" allImages = tuple(img for img in os.listdir(path) if img.endswith(".JPG")) def renameFile(index, path, fileName, renameTo): print "%d. Renamed: %s to %s" % (

我正在努力学习python中的线程

到目前为止,这是我写的一个简单的小菜一碟:

path = "/Users/userName/Desktop/temp/bluetooth"
allImages = tuple(img for img in os.listdir(path) if img.endswith(".JPG"))

def renameFile(index, path, fileName, renameTo):
    print "%d. Renamed: %s to %s" % (index, fileName, renameTo)
    os.rename(os.path.join(path, fileName), os.path.join(path, renameTo))
    return

def threadedRename():
    for  ind, img in enumerate(allImages):
        t = threading.Thread(target=renameFile, args=(ind, path, img, "%s%s" % (ind, img)))
        t.start()
threadedRename()
上面的代码是否通过每个线程同时重命名文件?它有意义吗?如果有,我如何检查上面的代码和下面的代码所花费的重命名时间之间的差异

# perform rename one by one
for ind, img in enumerate(allImages):
    print "Renaming: %s" % img
    os.rename(os.path.join(path, img), os.path.join(path, "%s%s" % (ind, img)))

我认为在这里为每个文件创建一个线程是不值得的。重命名操作不是很长,以证明为每个文件创建线程的开销是合理的。如果您有很多文件,那么创建几个线程并让它们成批完成工作是值得的

为了给程序计时,请使用
time.clock()


作为学习线程的编程练习,这没有什么错,但它不是线程的一种很好的实际用途。这些都是操作系统和存储硬件需要优化的事情,而在物理磁盘上,您必须违反物理定律才能同时进行优化

计时器代码的重要部分是“#执行操作”部分。您需要在创建线程时列出线程列表,然后执行以下操作以获取线程的实际运行时间:

# start timer

# start all the threads
for t in renameThreads:
    t.start

# wait for all threads to finish
for t in renameThreads:
    t.join()

# now you can stop the timer

也许也取决于一些文件,其他的方法是否正确?
# start timer

# start all the threads
for t in renameThreads:
    t.start

# wait for all threads to finish
for t in renameThreads:
    t.join()

# now you can stop the timer