How to Write Data into CSV Format as String (Not File)

How do I write data into CSV format as string (not file)?

You could use StringIO instead of your own Dummy_Writer:

This module implements a file-like class, StringIO, that reads and writes a string buffer (also known as memory files).

There is also cStringIO, which is a faster version of the StringIO class.

Python: How to create a csv string (no file) from a list of dictionaries?

You can use io.StringIO to write to a 'string' instead of a file. Using the example of csv.DictWriter we get the following code:

import csv
import io

data = [...] # your list of dicts

with io.StringIO() as csvfile:
fieldnames = ['id', 'col1', 'col2', 'col3']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

writer.writeheader()
for row in data:
writer.writerow(row)
print(csvfile.getvalue())

Writing data into CSV file in C#

UPDATE

Back in my naïve days, I suggested doing this manually (it was a simple solution to a simple question), however due to this becoming more and more popular, I'd recommend using the library CsvHelper that does all the safety checks, etc.

CSV is way more complicated than what the question/answer suggests.

Original Answer

As you already have a loop, consider doing it like this:

//before your loop
var csv = new StringBuilder();

//in your loop
var first = reader[0].ToString();
var second = image.ToString();
//Suggestion made by KyleMit
var newLine = string.Format("{0},{1}", first, second);
csv.AppendLine(newLine);

//after your loop
File.WriteAllText(filePath, csv.ToString());

Or something to this effect.
My reasoning is: you won't be need to write to the file for every item, you will only be opening the stream once and then writing to it.

You can replace

File.WriteAllText(filePath, csv.ToString());

with

File.AppendAllText(filePath, csv.ToString());

if you want to keep previous versions of csv in the same file

C# 6

If you are using c# 6.0 then you can do the following

var newLine = $"{first},{second}"

EDIT

Here is a link to a question that explains what Environment.NewLine does.

How to write a dictionary of lists to a string instead of CSV file?

Each of the values in csvdata.values() is a list of values for its corresponding key / column, so you are effectively printing the columns of the table as rows.

Instead, construct the rows by ziping the value lists:

csvfile += ",".join(csvdata.keys()) + "\n"
for row in zip(*csvdata.values()):
csvfile += ",".join(row) + "\n"

Output:

ID,Name,Gender
101,X,M
102,Y,F

How to write to a CSV line by line?

General way:

##text=List of strings to be written to file
with open('csvfile.csv','wb') as file:
for line in text:
file.write(line)
file.write('\n')

OR

Using CSV writer :

import csv
with open(<path to output_csv>, "wb") as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for line in data:
writer.writerow(line)

OR

Simplest way:

f = open('csvfile.csv','w')
f.write('hi there\n') #Give your csv text here.
## Python will convert \n to os.linesep
f.close()

string formating python to csv file

Manually increase the width of the column and you'll see the format changes.

Since you are writing a csv file (which, unlike xlsx, does not contain its own styling and formatting), it's not related to Python and there's nothing Python can do to make Excel use a specific format.

how to write a string which starts with - into csv file?

It's a problem with excel. When you open a CSV file in excel it tries to determine cell type automatically which usually fails. The CSV file is alright the editor is not ;)

You can either right click on the field, select Format Cell and there make it a text file (and you might need to remove the automatically inserted '=' sign). Or you can open the CSV file by going into Data - From Text/CSV and in the wizard select the proper column types.

How can I write a string to format row data to save as a CSV file?

As mentioned in another answer, the issue is that you are writing to the file inside the loop as you process each column, instead of after the loop, when you have collected all the column information for the row.

Another way you could do this is to use string.Join and System.Linq to more concisely concatenate the column values for each row.

Also note that we can wrap the csvFileWriter in a using block, so that it automatically gets closed and disposed when the block execution completes:

using (var csvFileWriter = new StreamWriter(CsvFpath, false))
{
// Write all the column headers, joined with a ','
csvFileWriter.WriteLine(string.Join(",",
stockGridView.Columns.Cast<DataGridViewColumn>().Select(col => col.HeaderText)));

// Grab all the rows that aren't new and, for each one, join the cells with a ','
foreach (var row in stockGridView.Rows.Cast<DataGridViewRow>()
.Where(row => !row.IsNewRow))
{
csvFileWriter.WriteLine(string.Join(",",
row.Cells.Cast<DataGridViewCell>().Select(cell => cell.Value.ToString())));
}
}

Another thing: Instead of writing your own csv parser, there are existing tools that you can use to write csv files, such as CsvHelper, which will handle other sorts of edge cases that can cause problems, such as values that have commas in them.



Related Topics



Leave a reply



Submit