how can i save different data to text file separated by commas and the text file shoul handle 5 records

Dani AI

Generated

Brief answer for Python 3: use the csv module (so fields with commas are quoted correctly), read the existing rows, append the new row, trim to the last five records, then write the file back atomically. That follows ’s idea of appending but adds the trim and safe write so the file never grows beyond five records. asked for code — here is a ready-to-run snippet you can drop into a script and adapt (replace new_row with your values).

import csv
import os
import tempfile
from pathlib import Path

file = Path('data.csv')
new_row = ['value1', 'value2', 'value3']  # replace with your data

# read existing rows
rows = []
if file.exists():
    with file.open(newline='', encoding='utf-8') as f:
        rows = list(csv.reader(f))

rows.append(new_row)
rows = rows[-5:]  # keep only last 5 records

# write atomically to avoid corruption
dirpath = file.parent or Path('.')
with tempfile.NamedTemporaryFile('w', delete=False, dir=dirpath, newline='', encoding='utf-8') as tmp:
    csv.writer(tmp).writerows(rows)
os.replace(tmp.name, file)

Notes and troubleshooting:

  • Use newline='' when working with csv on Python 3 to avoid extra blank lines on Windows.
  • If multiple processes might write at once, add a file lock (or use a small local DB like SQLite) to avoid races.
  • If you only ever append and want to avoid reading the whole file, stream into a collections.deque(maxlen=5) while reading, then write that deque back.
  • Use .csv extension for clarity and let the csv module handle quoting if your fields contain commas.
  • This approach is atomic (writes to a temp file then replaces), which prevents partial files if the script is interrupted.

Recommended Answers

All 4 Replies

What code have you got so far for this?

What is the data etc?

Hi

Does it mean to Export your Data from Datatable to Word Document?If so,I can provide you the following codes to achieve this.

**Step1. Function to fill data in datatable **

private void Form1_Load(object sender, EventArgs e)
        {
            oleDbConnection1.ConnectionString = txtConnectString.Text;
            oleDbCommand1.CommandText = txtCommandText.Text;
            using (OleDbDataAdapter da = new OleDbDataAdapter())
            {
                da.SelectCommand = oleDbCommand1;
                da.SelectCommand.Connection = oleDbConnection1;
                DataTable dt = new DataTable();
                da.Fill(dt);
                dataGridView1.DataSource = dt;
            }
        }

Step2. Export Data to word document

private void btnExportToWord_Click(object sender, EventArgs e)
        {
            Spire.DataExport.RTF.RTFExport rtfExport = new Spire.DataExport.RTF.RTFExport();
            rtfExport.DataSource = Spire.DataExport.Common.ExportSource.DataTable;
            rtfExport.DataTable = this.dataGridView1.DataSource as DataTable;
            rtfExport.ActionAfterExport = Spire.DataExport.Common.ActionType.OpenView;
            RTFStyle rtfStyle = new RTFStyle();
            rtfStyle.FontColor = Color.Blue;
            rtfStyle.BackgroundColor = Color.LightGreen;
            rtfExport.RTFOptions.DataStyle = rtfStyle;
            rtfExport.FileName=@"..\..\ToWord.doc";
            rtfExport.SaveToFile();
        }

Alternatively,if you dont mind using a 3rd party data library,you can check this.Hope it helps.

from DataBase-> to textfile?
1.Create a File (ex: *.txt)
2.Fill DataTable object from Database using select command
3.using foreach the each row from that dataTableObject's data will append to a single string
4.append the string with already created *.txt file

System.IO.File.WriteAllText(@"c:\1.txt","");
DataTable dt=new DataTable();
SqlDataAdapter da = new SqlDataAdapter("select * from tbl2", con);
da.Fill(dt);
DataGridView1.DataSource = dt;
foreach DataRow drow In dt.Rows
{
  String str= drow("column1") + " " + drow("column2") + " " + drow("column3") + " ";
  File.AppendAllText(@"c:\1.txt",Environment.NewLine+str);
 }
 MessageBox.show("Data Exported Successfully");
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.