python - Using data from CSV to make directories -
i have .csv file such following:
name1,name2,name3 , on
using python script trying have read .csv , make directories each value eg: name1,name2,name3
create these directories :name1 , name2 , name3
this code far:
import os import fileinput textfile = 'e:/videos/movies/subtest/dirlist.csv' path = "e:/videos/movies/subtest/" #generate txt file current names of directories def makefile(): # open file dirs = os.listdir( path ) # print files , directories file in dirs: #open file tfo = open(textfile, "ab+") #write file, seprating each item "||" tfo.write( file + ',' ) #print output print ( file ) #prints confirmation print 'file printed!' #close file tfo.close() mainmenu() def makedirs(): #open textfile read , set varible mylistread mylistread = open(textfile, 'rb+') #reads x amount of lines , stores str str = mylistread.read(); line in str: os.makedirs(path + str) print 'directories created:', str
running code creates .csv intended, when run makedirs() makes directory name of .csv (name1,name2,name3 foldername)
your problems become obvious if add print
statements code.
given input file looks like:
name1,name2,name3
the following code:
str = mylistread.read(); line in str: print 'line:', line
would print:
line: n line: line: m line: e line: 1 line: , line: n line: line: m line: e line: 2 line: , line: n line: line: m line: e line: 3 line:
that is, you're iterating on characters, not comma delimited items. read()
method reads in entire file single string. sequence of characters, not sequence of lines.
if want iterate on lines in file, don't need call read()
, can this:
mylistread = open(textfile, 'rb+') line in mylistread: print 'line:', line
which yield:
line: name1,name2,name3
of course, you're going need split line on commas. this:
for line in mylistread: item in line.strip().split(','): os.makedirs(os.path.join(path, item)) print 'created', item
you think using built-in csv
module parsing csv file, although may overkill particular use case.
Comments
Post a Comment