I have several lists of various lengths that I am trying to export to CSV so they can be called up again later when the program is launched again. Everytime I try the following, it only outputs a single line of data to the csv:
export = [solutions, fedata, bbcom, fenxt, ten_99, ten_99links]
with open('test.csv','w') as f:
writer = csv.writer(f)
# writer.writerow([<header row>]) #uncomment this and put header, if you want header row , if not leave it commented.
for x in zip(*export):
writer.writerow(x)
some of the lists currently only have 1 item in them, but I am trying to basically make a CSV be a database for this program as we will be adding more to the lists as it is expanded. Any help is appreciated, I am really banging my head against the wall here.
I tried the pasted code but it only outputs a single line of data
Do you want every item to be on a newline or every list on a newline?
If you want an empty line between the prints then you can remove the newline=''
Try this:
with open('test.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(export)
Related
I have an input file that contains data in the same format repeatedly across 5 rows. I need to format this data into one row (CSV file) and have only few fields relevant to me. How do i achieve the mentioned output with the input file provided.
Note - I'm very new to learning any language and haven't reached to this depth of details yet to write my own. I have already written the code where i'm importing the input file, reaching to a specif word and then printing the rest of the data(this is where i need help as i don't need all the information in the input as using space is delimiter is not giving the output in correct columns). I have also written the code to write the output in a csv file.
Note 2 - I'm very to this forum as well and kindly excuse me in case i have made any posting in posting my query.
Input -
Input File
Output -
Output File
import itertools, csv
You should read in the file and parse it manually, then use the csv module to write it to a .csv file:
import re
with open('myfile.txt', 'r') as f:
lines = f.readlines()
# divide on whitespace characters, but not single spaces
lines = [re.split("\s\s+", line) for line in lines]
with open('output.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
for line in lines:
writer.writerow(lines)
But this will include every piece of data. You can iterate through lines and remove the fields you don't want to keep. So before you do the csv writing, you could do:
def filter_line(line):
# see how the input file was parsed
print(line)
# for example, only keep the first 2 columns
return [line[0], line[1]]
lines = [filter_line(line) for line in lines]
I am trying to create a script to reformat a .CSV file. The read file starts as pipe delimited and get written as comma.
All it needs to do is index the columns and output them to file the way I want.
I am able to make it work perfectly when printing the output to screen (see two commented lines at bottom of code), but when I attempt to write to file I get the following error. I have tried to change the format of csv_writer.writerow({'F3'}) several different ways. It would seem I don't completely understand how to use writerow(). Or if I am completely missing something to make it function properly.
I also have to put static fields in, in front of the index fields. (i.e I need a "1" put in front of the F3 field) Is there an additional trick to that?
import csv
csv.register_dialect('piper', delimiter='|')
with open('pbfile.txt', 'r') as csv_file:
csv_reader = csv.DictReader(csv_file, dialect='piper',quoting=csv.QUOTE_MINIMAL)
with open('ouput2.csv', 'w', newline='') as new_file:
fieldnames = ['F0','F1','F2','F3','F4','F5','F6']
csv_writer = csv.DictWriter(new_file, delimiter=',',fieldnames=fieldnames)
for line in csv_reader:
#csv_writer.writeheader()
csv_writer.writerow({'F3'})
csv_writer.writerow({'F1', 'F2', 'F6'})
#print('1', line['F3'])
#print('380', line['F1'], line['F2'], line['F6'])
I have the following problem. I have a for loop, in which i want to add always the newcoming element of a list to a new line in a csv file. But something is wrong with my code. If i open the file, there is alwys a space between the rows and the list brackets are also existing.
My code extract:
allParameterCombi.append([fRC_Network1.jc,fRC_Network1.radius,fRC_Network1.frcSize, fRC_Network1.percent[0],fRC_Network1.percent[1],fRC_Network1.distType, fRC_Network1.ID])
with open('parameterCombinatons.csv','a') as csv_file:
writer = csv.writer(csv_file, delimiter=";")
writer.writerow([allParameterCombi[count3-1]])
count3 = count3 +1
How it looks like opened:
You have to open your file in binary mode ("ab") before passing them to csv.writer like this:
with open('parameterCombinatons.csv','ab') as csv_file: #python3 open('parameterCombinatons.csv','a',newline='')
I have a plain .txt document that I'm splitting up into individual words, appending them into a list, and then I'm trying to write that list into an Excel file so that each word is a new cell in the file. No matter what I do though, my code keeps taking all the words in the string and puts them in one cell, instead of splitting it by word like I'd intended. If you can help, could you also help explain why your solution works or why mine was wrong? Thanks!
Here's what my code looks like right now:
import csv
list_of_words = []
with open('ExampleText.txt', 'r') as ExampleText:
for line in ExampleText:
for word in line.split():
print(word)
list_of_words.append(word)
print("Done!")
print("Also done!")
with open('Gazete.csv', 'wb') as WordsFromText:
writer = csv.writer(WordsFromText, delimiter=' ', dialect='excel')
writer.writerow(list_of_words)
Excel defaults to comma or tab delimited when opening from CSV regardless of what your delimiter was set to during the export from Python. Try using a delimiter of ',' if you are trying to put these words into a separate cell in the same row.
Remove the delimiter parameter from your call to csv.writer.
writer = csv.writer(WordsFromText, dialect='excel')
You don't need one when a dialect is specified.
i need to save 6 lists in csv file and load back when program open.help me please
this is one of my list and all the lists are updating these are some sample details
list_of_DVDsuppliers=[["a","m",15],["w","p",34]]
i tried this code but it wont work.
import csv
list_of_DVDsuppliers=[["a","m",15],["w","p",34]]
myfile = open("pppp.csv", 'wb')
wr = csv.writer(myfile, quoting=csv.QUOTE_NONE)
wr.writerow(list_of_DVDsuppliers)
myfile.close
1.help me to save and read in csv?
still need help.................
You want
wr.writerows(list_of_DVDsuppliers)
with an s, because you're writing more than one row.
As well,
myfile.close
doesn't do anything: you want
myfile.close()
to actually call it, not merely mention the name.
Better would be to use a with block:
with open("pppp.csv", "wb") as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_NONE)
wr.writerows(list_of_DVDsuppliers)
because then you never have to remember to close the file, it's done automatically.
This produces a file looking like
a,m,15
w,p,34
which I'm guessing is what you want (you might want the list flattened and written as one row instead.)
[PS: I'm assuming Python 2 here. Othewise it should be open("pppp.csv", "r", newline='').]