Yes, I know this question has been asked but I have tried the other solutions and also my situation is different, since I am writing to stdout. For example I would type in cmd line python file1.csv file2.csv > results.csv
However, my output.csv file ends up like
hash,type,file
c02107d09c89bc369a6b6,Misc,items.csv
b20e07d09c89bc369a6b6,Other,items.csv
with each row being all in one cell ( the leftmost starting cell ) and skipping a row each time.
My code is this:
filenames = argv[1:]
header = True
for filename in filenames:
# Read from file
with open(filename) as csv_file:
# Get the file name from the path
filename = os.path.basename(filename)
# Get a reader to iterate each csv row
csv_reader = csv.reader(csv_file, delimiter=',')
# Add the categories header at the top only
if header:
categories = csv_reader.__next__()
categories.append("file")
self.results.append(categories)
header = False
else:
csv_reader.__next__() # Skip type
for row in csv_reader:
row.append(filename)
self.results.append(row)
# Write CSV output to stdout
csv_writer = csv.writer(sys.stdout)
csv_writer.writerows(self.results)
I have tried stuff like this with open('file.csv', 'w', newline='') as f: writer = csv.writer(f, delimiter=',')
and other things like using with
to open as sys.stdout
and nothing works. I've also reviewed a dozen other posts of the same topic and nothing works. Please help!