I need help in writing code to print output to csv file. The code is posted below. Appreciate your help.
import csv
result = {}
with open('data.csv', 'rb') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',', quotechar='"')
for row in csvreader:
if row[0] in result:
result[row[0]].append(row[1])
else:
result[row[0]] = [row[1]]
print(result)
Use csv.writer to write the rows in result to an output stream:
with open('output.csv', 'w') as csvfile:
csvwriter = csv.writer(csvfile)
for row in result.items():
csvwriter.writerow(row)
Related
I need to select the values of a specific parameter from csv file and copy the output to a new csv file.
I have an issue with saving the output to a new file.
import pandas as pd
import csv
import codecs
myifile=open('Log_01.csv',"rb")
read=csv.reader(codecs.iterdecode(myifile, 'UTF-8'))
myList=['11:PRTD 1']
for row in read:
if row[0] in myList:
print(row)
[enter image description here][1]
import csv
with open('Log_01.csv', newline='') as csvfile:
with open('eggs.csv', 'w', newline='') as csvfileWrite:
spamreader = csv.reader(csvfile, delimiter=',')
spamwriter = csv.writer(csvfileWrite, delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
for row in spamreader:
spamwriter.writerow(row)
I have a txt data. it looks as follows
time pos
0.02 1
0.1 2
...
and so on. so the each line is separated with a space. I need to convert it in to a CSV file. like
time,pos
0.02,1
0.1,2
0.15,3
How can I do it with python ? This is what I have tried
time = []
pos = []
def get_data(filename):
with open(filename, 'r') as csvfile:
csvFileReader = csv.reader(csvfile)
next(csvFileReader)
for row in csvFileReader:
time.append((row[0].split(' ')[0]))
pos.append((row[1]))
return
with open(filename) as infile, open('outfile.csv','w') as outfile:
for line in infile:
outfile.write(line.replace(' ',','))
From here:
import csv
with open(filename, newline='') as f:
reader = csv.reader(f, delimiter=' ')
for row in reader:
print(row)
For writing just use default options and it would save file with comma as a delimiter.
try:
import pandas as pd
with open(filename, 'r') as fo:
data = fo.readlines()
for d in range(len(data)):
if d==0:
column_headings = data[d].split()
data_to_insert = data[d].split()
pd.DataFrame(data_to_insert).to_excel('csv_file.csv', header=False, index=False, columns = column_headings))
You can use this:
import csv
time = []
pos = []
def get_data(filename):
with open(filename, 'r') as csvfile:
csvfile1 = csv.reader(csvfile, delimiter=' ')
with open(filename.replace('.txt','.csv'), 'w') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
for row in csvfile1:
writer.writerow(row)
I need to create a file and write its header contents before the for loop. If I do it inside the loop, header content repeats for every iteration of the loop. When I execute the below code, I get the error "I/O operation on a closed file".
Is wondering there a work around for this issue? Any suggestions would be appreciated. TIA !!
csv_filename = "testfile4.csv"
with open(csv_filename, "wt") as csvfile:
writer = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
# CSV Header
header = ["Post ID", "Permalink", "Create Time"]
writer.writerow(header)
for group in getGroups():
feed = getValues(group["id"], group["name"])
with open(csv_filename, "a") as csvfile:
for item in feed:
row = [item["id"], item["permalink_url"], item["created_time"]]
writer.writerow(row)
You could process all necessary operations in single with statement
csv_filename = "testfile4.csv"
with open(csv_filename, "wt") as csvfile:
writer = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
header = ["Post ID", "Permalink", "Create Time"]
writer.writerow(header)
for group in getGroups():
feed = getValues(group["id"], group["name"])
for item in feed:
row = [item["id"], item["permalink_url"], item["created_time"]]
writer.writerow(row)
I have data that look like below
id,Stage1Pow1,Stage1Pow2,Stage2Pow1,Stage2Pow2
A,1.0,1.5,1.1,1.4
B,0.9,1.2,0.9,1.1
C,1.0,1.0,0.8,0.8
how do I convert them into below format, in order to store and further analyze by stage.
id,StageNo,Pow1,Pow2
A,s1,1.0,1.5
A,s2,1.1,1.4
B,s1,0.9,1.2
B,s2,0.9,1.1
C,s1,1.0,1.0
C,s2,0.8,0.8
I'm very new to Python.
Let 'raw' be your input file name, and 'output' be your output file name.
import csv
data = []
with open('raw', 'r') as f:
csvreader = csv.reader(f, delimiter=',')
for row in csvreader:
data.append(row)
with open('output', 'w') as f:
csvwriter = csv.writer(f)
csvwriter.writerow(['id', 'StageNo', 'Pow1', 'Pow2'])
for row in data[1:]:
csvwriter.writerow([row[0], 's1', row[1], row[2]])
csvwriter.writerow([row[0], 's2', row[3], row[4]])
more info on https://docs.python.org/2/library/csv.html
You can use csv modules csv.DictReader() and csv.DictWriter()
import csv
with open('input.csv','r') as file:
reader = csv.DictReader(file)
with open('output.csv','w') as file_output:
writer = csv.DictWriter(file_output,fieldnames=['id','StageNo','Pow1','Pow2'])
writer.writeheader()
for line in reader:
line_split1 = {'id':line['id'],'StageNo':'s1','Pow1':line['Stage1Pow1'],'Pow2':line['Stage1Pow2']}
line_split2 = {'id':line['id'],'StageNo':'s2','Pow1':line['Stage2Pow1'],'Pow2':line['Stage2Pow2']}
writer.writerows([line_split1,line_split2])
Output:
id,StageNo,Pow1,Pow2
A,s1,1.0,1.5
A,s2,1.1,1.4
B,s1,0.9,1.2
B,s2,0.9,1.1
C,s1,1.0,1.0
C,s2,0.8,0.8
EDIT: Thanks for the answers guys, got what I needed!!
Basically I am trying to take what I have stored in my textfile and I am trying to write that into a .csv file. In my file are tweets that I have stored and I am trying to have one tweet in each cell in my .csv file.
Right now it is only taking one tweet and creating a .csv file with it and I need it to take all of them. Any help is greatly appreciated. Here is what I have so far.
with open('reddit.txt', 'rb') as f:
reader = csv.reader(f, delimiter=':', quoting = csv.QUOTE_NONE)
for row in reader:
print row
cr = csv.writer(open('reddit.csv', 'wb'))
cr.writerow(row)
You'll need to create the writer outside of the loop:
with open('reddit.txt', 'rb') as input_file:
reader = csv.reader(input_file, delimiter=':', quoting = csv.QUOTE_NONE)
with open('reddit.csv', 'wb') as output_file:
writer = csv.writer(output_file)
for row in reader:
writer.writerow(row)
Although here it might be cleaner to open the files without with:
input_file = open('reddit.txt', 'rb')
output_file = open('reddit.csv', 'wb')
reader = csv.reader(input_file, delimiter=':', quoting=csv.QUOTE_NONE)
writer = csv.writer(output_file)
for row in reader:
writer.writerow(row)
input_file.close()
output_file.close()
Or you can still use with and just have a really long line:
with open('reddit.txt', 'rb') as input_file, open('reddit.csv', 'wb') as output_file:
reader = csv.reader(input_file, delimiter=':', quoting = csv.QUOTE_NONE)
writer = csv.writer(output_file)
for row in reader:
writer.writerow(row)
The line cr = csv.writer(open('reddit.csv', 'wb')) is inside the for loop. You need to open the file just once, place this line after
reader = csv.reader(f, delimiter=':', quoting = csv.QUOTE_NONE)
Then write to it as you did in each loop iteration.