Search code examples
pythonfilemovedirectory

How to move numbered files into numbered folders using Python?


I have a series of files named mesh1, mesh2, mesh3, and so forth. I would like to create corresponding folders, like folder1, folder2, folder3 and so on. I would also like to put the files into the folders. For example, mesh1 should go into folder1, mesh2 should go into folder2, etc.

Here is the code I use to create the folders:

for i in lst:
    os.makedirs("/home/tianxiangwang/Desktop/Simulation/File{}".format(i))

How can I move the files to the folders? I tried this but it doesn't work:

os.rename("/home/tianxiangwang/Desktop/Simulation/Mesh{}.txt".format(i), "/home/tianxiangwang/Desktop/Simulation/File{}/Mesh{}.txt".format(i))

Solution

  • The following code worked for me.

    for item in items:
        os.makedirs("/home/tianxiangwang/Desktop/Simulation/"+str(item))
        fil="/home/tianxiangwang/Desktop/Simulation/"+str(item)+"/"+str(item)+".txt"
        os.rename("/home/tianxiangwang/Desktop/Simulation/"+str(item)+".txt",fil)