Writing to csv breaks string to characters - python

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])

Related

How to fix "Error: iterable expected, not int" when writing to a CSV file?

Why is my CSV write function not working? This seems to be a very simple code but the CSV writerow is asking for an iterable. I just need to write the 1,2,3 in a column.
import csv
data = [1,2,3]
output = 'output.csv'
with open(output,'w') as f:
writer = csv.writer(f)
for item in data:
writer.writerow(item)
You are passing an integer but a list is expected.
import csv
data = [[1],[2],[3]]
output = 'output.csv'
with open(output,'w') as f:
writer = csv.writer(f)
for item in data:
writer.writerow(item)
We need to provide a list to the CSV writer writerow function, in which there are values for 1 complete row.
e.g
import csv
data = [1,2,3]
output = 'output.csv'
with open(output,'w') as f:
writer = csv.writer(f)
writer.writerow(data) # as data includes only 1 row. For multiple rows write every row with a loop

Python, write csv single row, multiple column

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()

Add a new column to a csv file in python

I am trying to add a column to a csv file that combines strings from two other columns. Whenever I try this I either get an output csv with only the new column or an output with all of the original data and not the new column.
This is what I have so far:
with open(filename) as csvin:
readfile = csv.reader(csvin, delimiter=',')
with open(output, 'w') as csvout:
writefile = csv.writer(csvout, delimiter=',', lineterminator='\n')
for row in readfile:
result = [str(row[10]) + ' ' + str(row[11])]
writefile.writerow(result)
Any help would be appreciated.
No input to test, but try this. Your current approach doesn't include the existing data for each row that already exists in your input data. extend will take the list that represents each row and then add another item to that list... equivalent to adding a column.
import csv
with open(filename) as csvin:
readfile = csv.reader(csvin, delimiter=',')
with open(output, 'w') as csvout:
writefile = csv.writer(csvout, delimiter=',', lineterminator='\n')
for row in readfile:
row.extend([str(row[10]) + ' ' + str(row[11])])
writefile.writerow(row)
I assume that glayne wants to combine column 10 and 11 into one.
In my approach, I concentrate on how to transform a single row first:
def transform_row(input_row):
output_row = input_row[:]
output_row[10:12] = [' '.join(output_row[10:12])]
return output_row
Once tested to make sure that it works, I can move on to replace all rows:
with open('data.csv') as inf, open('out.csv', 'wb') as outf:
reader = csv.reader(inf)
writer = csv.writer(outf)
writer.writerows(transform_row(row) for row in reader)
Note that I use the writerows() method to write multiple rows in one statement.
Below code snippet combines strings in column 10 and column 11 in each row and add that to the end of the each row
import csv
input = 'test.csv'
output= 'output.csv'
with open(input, 'rb') as csvin:
readfile = csv.reader(csvin, delimiter=',')
with open(output, 'wb') as csvout:
writefile = csv.writer(csvout, delimiter=',', lineterminator='\n')
for row in readfile:
result = row + [row[10]+row[11]]
writefile.writerow(result)

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.]

Separate data with a comma CSV Python

I have some data that needs to be written to a CSV file. The data is as follows
A ,B ,C
a1,a2 ,b1 ,c1
a2,a4 ,b3 ,ct
The first column has comma inside it. The entire data is in a list that I'd like to write to a CSV file, delimited by commas and without disturbing the data in column A. How can I do that? Mentioning delimiter = ',' splits it into four columns on the whole.
Just use the csv.writer from the csv module.
import csv
data = [['A','B','C']
['a1,a2','b1','c1']
['a2,a4','b3','ct']]
fname = "myfile.csv"
with open(fname,'wb') as f:
writer = csv.writer(f)
for row in data:
writer.writerow(row)
https://docs.python.org/library/csv.html#csv.writer
No need to use the csv module since the ',' in the first column is already part of your data, this will work:
with open('myfile.csv', 'w') as f:
for row in data:
f.write(', '.join(row))
f.write('\n')
You could try the below.
Code:
import csv
import re
with open('infile.csv', 'r') as f:
lst = []
for line in f:
lst.append(re.findall(r',?(\S+)', line))
with open('outfile.csv', 'w', newline='') as w:
writer = csv.writer(w)
for row in lst:
writer.writerow(row)
Output:
A,B,C
"a1,a2",b1,c1
"a2,a4",b3,ct

Categories

Resources