[英]Use Python to Create Folders Recursively with Folder Names Matching Filenames
Is there a Python method to create directories recursively? 是否有Python方法来递归创建目录? I have this path:
我有这条路:
/home/data/ with files 'table1.csv', 'table2.csv', ... , 'table1000.csv' in it / home / data /中包含文件“ table1.csv”,“ table2.csv”,...,“ table1000.csv”
I would like to create: /home/data/table1 and move 'table1.csv' in it; 我想创建:/ home / data / table1并在其中移动“ table1.csv”; /home/data/table2 and move 'table2.csv' in it;
/ home / data / table2并在其中移动“ table2.csv”; .
。 .
。 .
。 /home/data/table1000 and move 'table1000.csv' in it;
/ home / data / table1000并在其中移动“ table1000.csv”;
The folder names would have to match the csv file names. 文件夹名称必须与csv文件名称匹配。
How can I do it recursively? 我该如何递归呢? I know os.makedirs() should probably be used not sure how it works exactly.
我知道应该使用os.makedirs()不确定它是如何工作的。
Many thanks. 非常感谢。
NOTE: 'table1' and 'table2' etc are just dummy example file names. 注意:“ table1”和“ table2”等只是虚拟示例文件名。 The real filenames are a bit complex.
实际的文件名有点复杂。
Use mkdir
to create each dir, from the os
library. 使用
mkdir
从os
库创建每个目录。
https://docs.python.org/2/library/os.html https://docs.python.org/2/library/os.html
For each dir move the current file using shutil.move
. 对于每个目录,请使用
shutil.move
移动当前文件。
How to move a file in Python 如何在Python中移动文件
Each iteration should look like this: 每次迭代应如下所示:
for i in range(1, 1001):
os.mkdir('/home/data/table' + str(i))
shutil.move('/home/data/table' + str(i) + '.csv', '/home/data/table' + str(i) + '/table' + str(i) + '.csv')
I would work the following way in Python: 我将以以下方式在Python中工作:
1.Get all files in folder in a list 1.获取列表中文件夹中的所有文件
2.Loop Through the filenames of the list and: 2.浏览列表的文件名并:
A simple search in the net would get you ready examples on how to do each step of the above. 在网上进行简单的搜索即可获得有关如何完成上述每个步骤的示例。
Edit: Below a simple example for csv files. 编辑:下面是一个简单的csv文件示例。
import glob, os
import shutil
dir="D:\Dropbox\MYDOCS\DEV\python\snippets"
os.chdir(dir)
for file in glob.glob("*.csv"):
dst=dir+"\\"+file.replace(" ","_").replace(".csv","")
os.mkdir(dst)
print(dst)
shutil.move(file,dst)
Used windows paths, since I use windows, you ll need to change that to linux paths. 使用的Windows路径,因为我使用Windows,所以您需要将其更改为Linux路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.