2013-07-31 65 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相同的目錄。 –