Python csv writing - python

I'm trying to write to a csv file using excel.
with open('Daily.csv', 'w') as f:
writer = csv.writer(f, delimiter=';')
writer.writerow(["Sales Order;Company Name;Ship Date"])
This results in the following text being put into A1 and only A1.
Sales Order;Company Name;Ship Date
It appears the delimiter isn't working at all. I would like the data to be across three columns, not just one.

use writer.writerow(["Sales Order", "Company", "Name", "Ship Date"])

delimiter parameter of the csv.writer function doesn't set the delimiter for the data you want to write but for the file, so if you use the solution by Oleg you'll get a file with values delimited by ";". csv.writer.writerow needs the list of values.

Related

Is that possible to combine two csv files into one as mentiioned below

I am trying to combine csv file into one as below mentioned
input1:
Name,Age,Department
Birla,52,Welding
Rob,45,Furnace
input2:
YearofService,Audit
14,Y
8,N
My expected output :
Name,Age,Department,YearofService,Audit
Birla,52,Welding,14,Y
Rob,45,Furnace,8,N
My code :
with open('input1.csv','r') as i,open('input2.csv','r') as o:
reader=csv.reader(i)
fieldnames=reader.fieldnames
reader1=csv.reader(o)
fieldnames_1=reader1.fieldnames
#here reading the fieldnames and combine csv file as 1:
I dont need to uuse python pandas.is that possible to achieve using csv library?
help me on this.
Instead of writing into sepearate ouput file,if its we ad the input to input1 is also fine
You can simply read both files at the same time and combine the rows to create a new one (or write over one of them). Here is one example on how you can do it, but you can adapt to your needs.
import csv
with open('input1.csv','r') as input1, open('input2.csv', 'r') as input2:
with open('output.csv', 'w') as output:
writer = csv.writer(output, lineterminator='\n')
reader1 = csv.reader(input1)
reader2 = csv.reader(input2)
rows = []
for row1, row2 in zip(reader1, reader2):
rows.append(row1 + row2)
writer.writerows(rows)
Side note: don't forget that the best way to join CSVs are using common indexes, so the rows keep aligned. Python default CSV library is basic and ideally a better tool for dealing with them should be used, such as Pandas.

How to convert .dat to .csv using python? the data is being expressed in one column

Hi i'm trying to convert .dat file to .csv file.
But I have a problem with it.
I have a file .dat which looks like(column name)
region GPS name ID stop1 stop2 stopname1 stopname2 time1 time2 stopgps1 stopgps2
it delimiter is a tab.
so I want to convert dat file to csv file.
but the data keeps coming out in one column.
i try to that, using next code
import pandas as pd
with open('file.dat', 'r') as f:
df = pd.DataFrame([l.rstrip() for l in f.read().split()])
and
with open('file.dat', 'r') as input_file:
lines = input_file.readlines()
newLines = []
for line in lines:
newLine = line.strip('\t').split()
newLines.append(newLine)
with open('file.csv', 'w') as output_file:
file_writer = csv.writer(output_file)
file_writer.writerows(newLines)
But all the data is being expressed in one column.
(i want to express 15 column, 80,000 row, but it look 1 column, 1,200,000 row)
I want to convert this into a csv file with the original data structure.
Where is a mistake?
Please help me... It's my first time dealing with data in Python.
If you're already using pandas, you can just use pd.read_csv() with another delimiter:
df = pd.read_csv("file.dat", sep="\t")
df.to_csv("file.csv")
See also the documentation for read_csv and to_csv

How to write a list into column of another csv file using python

I have one csv file(name.csv) which contains the names a list of email address. I am trying to write one csv file with name as it's first column and email as it's second column. But in my final.csv the names are written properly but the emails are written one in a cell. Here is my code snippet.
data = [['Email'], ['connect#viu.ca', 'worldviu#viu.ca', 'registration#viu.ca', 'study#viu.ca', 'advising#viu.ca', 'advising.international#viu.ca', 'info#viu.ca' ], ['[]']]
with open('name.csv') as robj1, open('final.csv', 'w', newline='') as wobj:
csv_read = reader(robj1)
csv_writer = writer(wobj)
for row in csv_read:
row.append(data[i])
csv_writer.writerow(row)
i+=1
and the output i am getting is
and my desired output is
[
Your data list is a double list. Change it to a single list like this
data = [['Email'], ['connect#viu.ca', 'worldviu#viu.ca', 'registration#viu.ca', 'study#viu.ca', 'advising#viu.ca', 'advising.international#viu.ca', 'info#viu.ca' ], ['[]']]
Final.csv will be something like this
EDIT: To get rid of the other bracket
row.append(", ".join(data[i]))
Output will look like this.

How can I put every list of lists in a csv column in python?

I'm developing a script in python that gets data from a log file and I need to save every type of data into a respective column. I'm using regex to obtain the data.
This is a part of my code where I get this result:
#Getting data from log as list using regex
fecha = re.findall('\d{4}\-\d{2}\-\d{2}', str(listaValores))
hora = re.findall('\d{2}\:\d{2}\:\d{2}', str(listaValores))
#List of lists about data obtained
valoresFinales = [fecha, hora]
#Putting into .csv
with open("resultado.csv", "w") as f:
wr = csv.writer(f, delimiter=';')
wr.writerows(valoresFinales)
What I want
You give the writerows function a list of two elements, so you get two rows of data in the end.
Instead you want to give it something like zip(fecha, hora):
with open("resultado.csv", "w") as f:
wr = csv.writer(f, delimiter=';')
wr.writerows(zip(*valoresFinales))

Python - Printing individual cells from an Excel spreadsheet in CSV format

I have an excel spreadsheet saved as a CSV file, but cannot find a way to call individual values from cells into Python using the CSV module. Any help would be greatly appreciated
There is also a Python library capable of reading xls data. Have a look at python-xlrd.
For writing xls data, you can use python-xlwt.
The csv module provide readers that iterate over the rows of a csv file - the rows are lists of strings. One way to get access to individual cells would be to:
Read the entire file in as a list of lists
import csv
with open('test.csv', 'r') as f:
reader = csv.reader(f)
the_whole_file = list(reader)
Then access the individual cells by indexing into the_whole_file. The first index is the row and the second index is the column - both are zero based. To access the cell at the second row, fourth column:
row = 1
column = 3
cell_R1_C3 = the_whole_file[row][column]
print cell_R1_C3
If you have the excel file as a CSV, you can use csv.reader
import csv
myFilePath = "/Path/To/Your/File"
with open(myFilePath,'rb') as csvfile:
reader = csv.reader( csvfile, delimiter=',' )
for row in reader:
# 'row' has all the cells (thanks to wwii for the fix!). Get the first 4 columns
a, b, c, d = row[:4]

Categories

Resources