简体   繁体   English

如何使用python将一堆文本文件移动到其相应的文件夹中?

[英]How to move a bunch of textfiles into its corresponding folders using python?

I created couple of txt files based on a list[1,2,3,....,i] , namely mesh1, mesh2,....,mesh(i), I would like to create corresponding folders folder1, folder2,....,folder(i) and put the txt files into its folders. 我基于列表[1,2,3,....,i]创建了几个txt文件,分别是mesh1,mesh2,....,mesh(i),我想创建相应的文件夹folder1,folder2 ,....,folder(i)并将txt文件放入其文件夹中。 For example, mesh1 to folder1, mesh(i) to folder (i). 例如,mesh1到folder1,mesh(i)到文件夹(i)。

for i in lst:
os.makedirs("/home/tianxiangwang/Desktop/Simulation/File{}".format(i)) #This is to create multiple folders

Which commands should I use for the next step to move the files to the folders? 下一步应使用哪些命令将文件移动到文件夹?

I tried this but it obviously doesn't work. 我试过了,但显然不起作用。

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

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM