Can anyone help me in deleting a row in a text file....


Thanks.

Dani AI

Generated

opened this thread asking how to delete a row from a text file. requested details and posted a C# read-modify-write example that removes a 0-based line and rewrites the file. The same concept applies in Python, but two practical points matter: small files can be read into a list and rewritten, while larger files should be processed line-by-line into a temporary file and then atomically replace the original to avoid data loss or high memory use.

A safe Python pattern that streams into a temp file in the same directory and then replaces the original:

import os
import tempfile

def delete_line(filename, line_no):
    # line_no is 0-based
    dirn = os.path.dirname(filename) or '.'
    fd, tmp_path = tempfile.mkstemp(dir=dirn)
    try:
        with os.fdopen(fd, 'w', encoding='utf-8') as tmp, open(filename, 'r', encoding='utf-8') as src:
            for i, line in enumerate(src):
                if i == line_no:
                    continue
                tmp.write(line)
        os.replace(tmp_path, filename)
    except:
        try:
            os.unlink(tmp_path)
        except OSError:
            pass
        raise

Notes and troubleshooting: confirm whether the indexing is 0-based (as in 's example) or 1-based for the calling code. For CSVs, use the csv module to preserve quoting and delimiters. If multiple processes may access the file, consider locking. Test on a copy first and ensure the correct encoding. See the Python tempfile docs and fileinput docs for alternatives, and the csv module for CSV-specific work.

Recommended Answers

All 2 Replies

Can you please be more specific about your problem.......
:)

/// <summary>
    /// 
    /// </summary>
    /// <param name="FileName"></param>
    /// <param name="LineNumber">The 0-based line number</param>
    private static void DeleteLineNumber(string FileName, int LineNumber)
    {
      if (!File.Exists(FileName))
        throw new FileNotFoundException("File not found.", FileName);
      if (LineNumber < 0)
        throw new ArgumentOutOfRangeException("LineNumber", "Must be >= 0");
      List<string> lst = File.ReadAllLines(FileName).ToList();
      lst.RemoveAt(LineNumber);
      File.WriteAllLines(FileName, lst.ToArray());
    }
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.