2011-01-12 47 views
0

我想在python中编写一个程序,它将为具有相同名称的目录(本地)中的每个文件创建一个文件夹,然后将该文件移动到该文件夹​​中。我一直在寻找正确的代码或位,但我无法找到(或识别)它。任何帮助(或提示)将非常感激。我非常喜欢python。如何将_path_设置为变量?

+1

请描述您的输入和所需的输出。目前还不清楚你究竟在问什么。 – Dustin

+0

问题结果与问题内容不符。 – systemovich

回答

3

这做什么,我想你问:

#!/usr/bin/env python 

import os 

allfiles = [fn for fn in os.listdir('.') if not os.path.isdir(fn)] 

for fn in allfiles: 
    # The file must be moved out of the way before you can create a 
    # directory with the same name. 
    tmpname = fn + ".tmp" 
    # Then we're going to create filename/filename to store it in 
    newname = os.path.join(fn, fn) 

    # First, move it out of the way 
    os.rename(fn, tmpname) 
    # Then create the directory 
    os.mkdir(fn, 0777) 
    # So the file can be moved into it 
    os.rename(tmpname, newname) 
0

你想看看os模块和os.path模块。操作系统允许你创建目录和文件。 os.path允许你检查文件名和路径。