我有一个.csv文件,如下所示:
name1,name2,name3 and so on
使用Python脚本我试图让它读取.csv并为每个值创建目录
例如: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(name1,name2,name3作为foldername)
答案 0 :(得分: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文件,虽然这对您的特定用途可能过度
情况下。