Write Multiple Lists Into Csv. File In Python
Solution 1:
The issue is with the lines -
with open('some.csv', 'wb') as f: #Using `w` mode overwrites the file everytime
...
list3 = zip(list2) #This does not do what you think it does.
writer.writerows(list3) #This expects a list of rows, and writes each row on a single line.
First of all, list2
is a 1-dimensional list of strings (according to what you have created. When using zip()
directly on such lists, you get a list of tuples back, with each tuple having each element. Example -
>>> zip(['asd','sdf','dfg'])
[('asd',), ('sdf',), ('dfg',)]
You do not need to do this. Secondly, after this you use writer.writerows()
, this writes each tuple in your list3
into a single line, considering each tuple as a row. You want to use writer.writerow()
here . Example -
with open('some.csv', 'ab') as f:
writer = csv.writer(f)
writer.writerow(list2)
Solution 2:
You can construct a list of lists which can then be passed to csv.writer.writerows()
. Each of the nested lists corresponds to the values extracted from each file name; aim for a data structure like this:
data = [['value1', 'value 2', 'value3'],
['value1', 'value 2', 'value3'],
['value1', 'value 2', 'value3']]
data
can be written directly to a CSV file using csv.writer,writerows(data)
. Here is some code that should do what you want:
import os
import csv
def go():
search_strings = ('value1', 'value2', 'value3') # target strings to be found in file name
data = []
folder = folderentry.get() # reads path for 'folder'
for path, subdirs, files in os.walk(folder):
for name in files:
extracted_strings = []
for s in search_strings:
if s not in name:
s = 'NOT FOUND!'
extracted_strings.append(s)
data.append(extracted_strings)
with open('some.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerows(data)
This code builds up a list of lists (data
) which is then written to a CSV file in one operation. A refinement of the code above is to use a list comprehension to create the value list for each file name and append it directly to the data
list. This is more efficient and uses less code, but perhaps the first example is more understandable to you:
import os
import csv
def go():
search_strings = ('value1', 'value2', 'value3') # target strings to be found in file name
data = []
folder = folderentry.get() # reads path for 'folder'
for path, subdirs, files in os.walk(folder):
for name in files:
data.append([s if s in name else 'NOT FOUND!' for s in search_strings])
with open('some.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerows(data)
Post a Comment for "Write Multiple Lists Into Csv. File In Python"