2013-07-31 62 views
0

我有一个.csv文件,如下面的:使用Python脚本我试图把它读.csv和创建目录为每个值 如从CSV使用数据创建目录

name1,name2,name3 and so on 

name1,name2,name3将创建这些目录:name1 and name2 and name3

这是到目前为止我的代码:

import os 
import fileinput 
textFile = 'E:/Videos/Movies/subtest/dirlist.csv' 
path = "E:/Videos/Movies/subtest/" 

#generate a txt file with the current names of the directories 
def makeFile(): 
    # Open a file 
    dirs = os.listdir(path) 
    # This would print all the files and directories 
    for file in dirs: 
     #open the file 
     tFO = open(textFile, "ab+") 
     #write to the file, seprating each item with "||" 
     tFO.write(file + ',') 
     #print output 
     print (file) 
     #prints confirmation 
     print 'file printed!' 
     #close the file 
     tFO.close() 
    mainMenu() 

def makeDirs(): 
    #open textFile as read only and set its varible as myListRead 
    myListRead = open(textFile, 'rb+') 
    #reads the x amount of lines and stores it as str 
    str = myListRead.read(); 
    for line in str: 
     os.makedirs(path + str) 
    print 'directories created:', str 

运行该代码创建作为我打算将.csv,但当我运行makeDirs()它使所有的.csv的目录名(1,名称2,名称3作为文件夹名)

+2

你能澄清你的代码有什么问题吗? – Alex

+1

你的问题到底是什么? – BlackVegetable

+0

你能打印出你的os.makedirs的路径+ str,并将它张贴在这里吗? – sihrc

回答

2

如果你添加一些print 语句代码你的问题变得显而易见。

鉴于看起来输入文件,如:

name1,name2,name3 

下面的代码:

str = myListRead.read(); 
for line in str: 
    print 'LINE:', line 

将打印:

LINE: n 
LINE: a 
LINE: m 
LINE: e 
LINE: 1 
LINE: , 
LINE: n 
LINE: a 
LINE: m 
LINE: e 
LINE: 2 
LINE: , 
LINE: n 
LINE: a 
LINE: m 
LINE: e 
LINE: 3 
LINE: 

也就是说,你遍历字符,不是逗号分隔的项目。 read()方法将整个文件作为单个字符串读入。你 得到一个字符序列,而不是一系列的行。

如果要遍历文件中的行,你不需要调用 read(),你可以这样:

myListRead = open(textFile, 'rb+') 
for line in myListRead: 
    print 'LINE:', line 

这将产生:

LINE: name1,name2,name3 

中当然,你需要用逗号分割这一行。你 可以这样做:

for line in myListRead: 
    for item in line.strip().split(','): 
     os.makedirs(os.path.join(path, item)) 
     print 'created', item 

你也可以考虑使用内置csv模块用于解析 CSV文件,虽然这可能是矫枉过正的具体使用情况 。

+0

谢谢!代码的最后一部分为我工作,我也必须创建目录到一个新的文件路径,因为我不能创建2相同的目录。 –