Python, write csv single row, multiple column - python

Sorry for asking i have searched a lot but cant find what i need.
I need this list to be written to a csv file on one row(1) and each element from A to E
coluna_socio = ['bilhete', 'tipo', 'nome', 'idade', 'escalao']
outfile = open('socios_adeptos.csv', 'w', newline='')
writer = csv.writer(outfile)
for i in range(len(coluna_socio)):
writer.writerow([coluna_socio[i]])
Ive tried almost everything and it always write on on column or just in on cell(A1)
Thanks.

You can use the string join method to insert a comma between all the elements of your list. Then write the resulting string to file. The csv module isn't necessary in this case.
For example ...
with open('socios_adeptos.csv', 'w') as out:
out.write(','.join(coluna_socio))

You should call the csv.writer.writerow method with the list directly:
with open('socios_adeptos.csv', 'w', newline='') as outfile:
writer = csv.writer(outfile)
writer.writerow(coluna_socio)

I could write it in one row with your code, as follows:
coluna_socio = ['bilhete', 'tipo', 'nome', 'idade', 'escalao']
outfile = open('socios_adeptos.csv', 'w', newline='')
writer = csv.writer(outfile)
writer.writerow(coluna_socio)
outfile.close()

Related

How to add values to the column only and not a row? [duplicate]

I have a list of numbers that I want to put in a single column in a .csv file. The code below writes the values across a single row. How can I change the code so that Python writes the each value on a separate row? Thanks.
with open('returns.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerow(daily_returns)
With Python3, open the file in w mode:
with open('returns.csv', 'w') as f:
writer = csv.writer(f)
for val in daily_returns:
writer.writerow([val])
With Python2.6+, open the file in wb mode:
with open('returns.csv', 'wb') as f:
writer = csv.writer(f)
for val in daily_returns:
writer.writerow([val])
Alternate solution: Assuming daily_returns is the name of the list you wish to write as a column in a CSV file, the following code should work:
with open('return.csv','w') as f:
writer = csv.writer(f)
writer.writerows(zip(daily_returns))
Just for the record:
I'm using Python 3.2 and I could only get the following to work
with open('returns','w')as f:
writer=csv.writer(f,lineterminator='\n')
for val in returns:
writer.writerow([val])
For writing a single column, I would recommend avoiding the csv commands and just using plain python with the str.join() method:
with open('returns.csv', 'wb') as f:
f.write("\n".join(daily_returns))

Read CSV group by 1 column and apply sum, without pandas

As I wrote in the title I would like to read a CSV, do on this same CSV a group by column, apply sum, after replace the old CSV with the new values using as least libraries as possible (and avoid pandas). I have come this far:
index = {}
with open('event.csv') as f:
cr = reader(f)
for row in cr:
index.setdefault(row[0], []).append(int(row[1]))
f.close()
with open('event.csv', 'w', newline='\n') as csv_file:
writer = writer(csv_file)
for key, value in index.items():
writer.writerow([key, value[0]])
csv_file.close()
But in this way I can make the average…and also I have to open the file twice, which doesn't seem smart to me. Here is a CSV similar to event.csv:
work1,100
work2,200
work3,200
work1,50
work3,20
Desired output:
work1,150
work2,200
work3,220
You're actually very close. Just sum the values read while rewriting the file. Note that when using with on a file, you don't have to explicitly close them, it does it for you automatically. Also note that CSV files should be opened with newline=''—for reading and writing—as per the documentation.
import csv
index = {}
with open('event.csv', newline='') as csv_file:
cr = csv.reader(csv_file)
for row in cr:
index.setdefault(row[0], []).append(int(row[1]))
with open('event2.csv', 'w', newline='\n') as csv_file:
writer = csv.writer(csv_file)
for key, values in index.items():
value = sum(values)
writer.writerow([key, value])
print('-fini-')
The above could be written a little more concisely by eliminating some temporary variables and using a generator expression:
import csv
index = {}
with open('event.csv', newline='') as csv_file:
for row in csv.reader(csv_file):
index.setdefault(row[0], []).append(int(row[1]))
with open('event2.csv', 'w', newline='\n') as csv_file:
csv.writer(csv_file).writerows([key, sum(values)] for key, values in index.items())
print('-fini-')
Another simplification of solutions already shown, without additional libraries:
import csv
index = {}
with open('event.csv', newline='') as f:
cr = csv.reader(f)
for item,value in cr:
index[item] = index.get(item, 0) + int(value) # sum as you go
with open('event2.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(index.items()) # write all the items in one shot
print('-fini-')
With an additional library - convtools, which provides a lot of functionality not to write a lot of code by hand every time.
from convtools import conversion as c
from convtools.contrib.tables import Table
rows = Table.from_csv("event.csv", header=False).into_iter_rows(list)
converter = (
c.group_by(c.item(0))
.aggregate(
(
c.item(0),
c.ReduceFuncs.Sum(c.item(1).as_type(int)),
)
)
.gen_converter()
)
processed_rows = converter(rows)
Table.from_rows(processed_rows, header=False).into_csv(
"event2.csv", include_header=False
)
Here's another way to think of it.
Instead of storing arrays of ints during reading and then "compressing" them into the desired value during writing, show up-front that you're summing something during the read:
import csv
from collections import defaultdict
summed_work = defaultdict(int)
with open('event_input.csv', newline='') as f:
reader = csv.reader(f)
for row in reader:
work_id = row[0]
work_value = int(row[1])
summed_work[work_id] += work_value
with open('event_processed.csv', 'w', newline='') as f:
writer = csv.writer(f)
for work_id, summed_value in summed_work.items():
writer.writerow([work_id, summed_value])
This is functionally equivalent to what you were aiming for and what martineau helped you with, but, I argue, shows you and your reader sooner and more clearly what the intent is.
It technically uses one more library, defaultdict, but that's a standard library, and I'm not sure what value you're placing on the number of libraries being used.
EDIT
Oh, I just remembered there's the Counter class from collections, too. Might be even clearer:
summed_work = Counter()
and everything else is the same.

Writing to csv breaks string to characters

I am trying to write into a csv file, I have a hard coded header that I want to write:
head = ["Q151", "item time", "deliberativness", "deliberativness time",
"Q153", "item time", "deliberativness", "deliberativness time"]
But when I run the csv writer it is inserting every char into a different column, and every item in the list to a different row. so I am getting
Q 1 5 1
i t e m t i m e
and not Q151 item time ...
with open('some.csv', 'wb') as f:
writer = csv.writer(f)
for r in head:
writer.writerow(r)
I am using a simple writer like in the python docs. What am I doing wrong?
excepted result as I said above Q151 item time ...
You could use this code
with open('some.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerow(first_row)
Writer iterate your variable and write each element to the next cell.
When you give it string value, writer iterate it.
So to write all the lines you could add a loop.
with open('some.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerow(first_row)
list_of_rows = [['1', '2', '3'], ]
for row in list_of_rows:
writer.writerow(row)
# but better to use writerows
writer.writerows(list_of_rows)
You are doing it wrong. You can use the for loop when you have a list of lists/rows, and you want to wirte those into your file:
with open('some.csv', 'wb') as f:
writer = csv.writer(f, fieldnames=head)
writer.writeheader()
I finally figured it out! You simply just put the string in a list:
write.writerow([string])
For example:
with open('csv_file.csv', 'a') as f:
write = csv.writer(f)
write.writerow([string])

Create subset of large CSV file and write to new CSV file

I would like to create a subset of a large CSV file using the rows that have the 4th column ass "DOT" and output to a new file.
This is the code I currently have:
import csv
outfile = open('DOT.csv','w')
with open('Service_Requests_2015_-_Present.csv', newline='', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
if row[3] == "DOT":
outfile.write(row)
outfile.close()
The error is:
outfile.write(row)
TypeError: must be str, not list
How can I manipulate row so that I will be able to just straight up do write(row), if not, what is the easiest way?
You can combine your two open statements, as the with statement accepts multiple arguments, like this:
import csv
infile = 'Service_Requests_2015_-_Present.csv'
outfile = 'DOT.csv'
with open(infile, encoding='utf-8') as f, open(outfile, 'w') as o:
reader = csv.reader(f)
writer = csv.writer(o, delimiter=',') # adjust as necessary
for row in reader:
if row[3] == "DOT":
writer.writerow(row)
# no need for close statements
print('Done')
Make your outfile a csv.writer and use writerow instead of write.
outcsv = csv.writer(outfile, ...other_options...)
...
outcsv.writerow(row)
That is how I would do it... OR
outfile.write(",".join(row)) # comma delimited here...
In Above code you are trying to write list with file object , we can not write list that give error "TypeError: must be str, not list" you can convert list in string format then you able to write row in file. outfile.write(str(row))
or
import csv
def csv_writer(input_path,out_path):
with open(out_path, 'ab') as outfile:
writer = csv.writer(outfile)
with open(input_path, newline='', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
if row[3] == "DOT":
writer.writerow(row)
outfile.close()
csv_writer(input_path,out_path)
[This code for Python 3 version. In Python 2.7, the open function does not take a newline argument, hence the TypeError.]

Writing a Python list into a single CSV column

I have a list of numbers that I want to put in a single column in a .csv file. The code below writes the values across a single row. How can I change the code so that Python writes the each value on a separate row? Thanks.
with open('returns.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerow(daily_returns)
With Python3, open the file in w mode:
with open('returns.csv', 'w') as f:
writer = csv.writer(f)
for val in daily_returns:
writer.writerow([val])
With Python2.6+, open the file in wb mode:
with open('returns.csv', 'wb') as f:
writer = csv.writer(f)
for val in daily_returns:
writer.writerow([val])
Alternate solution: Assuming daily_returns is the name of the list you wish to write as a column in a CSV file, the following code should work:
with open('return.csv','w') as f:
writer = csv.writer(f)
writer.writerows(zip(daily_returns))
Just for the record:
I'm using Python 3.2 and I could only get the following to work
with open('returns','w')as f:
writer=csv.writer(f,lineterminator='\n')
for val in returns:
writer.writerow([val])
For writing a single column, I would recommend avoiding the csv commands and just using plain python with the str.join() method:
with open('returns.csv', 'wb') as f:
f.write("\n".join(daily_returns))

Categories

Resources