{"id":4234,"date":"2023-10-02T19:20:41","date_gmt":"2023-10-02T13:50:41","guid":{"rendered":"https:\/\/cbsepython.in\/?p=4234"},"modified":"2023-11-04T10:23:04","modified_gmt":"2023-11-04T04:53:04","slug":"python-program-to-delete-a-row-in-csv-file","status":"publish","type":"post","link":"https:\/\/cbsepython.in\/python-program-to-delete-a-row-in-csv-file\/","title":{"rendered":"Python Program To Delete a Row in CSV File"},"content":{"rendered":"<h2><span style=\"color: #000000;\">Python Program To Delete a Row in CSV File<\/span><\/h2>\n<p>&nbsp;<\/p>\n<h3><span style=\"color: #000000;\">Method-1<\/span><\/h3>\n<p><span style=\"color: #000000;\">You can delete a row in a CSV file in Python by reading the CSV file, excluding the row you want to delete, and then writing the remaining data back to the file. Here&#8217;s a Python program to do that:<\/span><\/p>\n<p>&nbsp;<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import csv\r\n\r\n# Specify the CSV file and the row index you want to delete\r\ncsv_file = 'example.csv'\r\nrow_index_to_delete = 2  # Replace with the index of the row you want to delete (0-based)\r\n\r\n# Read the CSV file and exclude the row to delete\r\ndata = []\r\nwith open(csv_file, 'r', newline='') as file:\r\n    csv_reader = csv.reader(file)\r\n    for index, row in enumerate(csv_reader):\r\n        if index != row_index_to_delete:\r\n            data.append(row)\r\n\r\n# Write the remaining data back to the CSV file\r\nwith open(csv_file, 'w', newline='') as file:\r\n    csv_writer = csv.writer(file)\r\n    csv_writer.writerows(data)\r\n\r\nprint(f\"Row {row_index_to_delete} deleted from {csv_file}\")\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p><span style=\"color: #000000;\">Make sure to replace <code>'example.csv'<\/code> with the path to your CSV file and set <code>row_index_to_delete<\/code> to the index of the row you want to delete (0-based index). This code will read the CSV file, exclude the specified row, and then overwrite the file with the updated data, effectively deleting the row.<\/span><\/p>\n<h3><span style=\"color: #000000;\">Method-2<\/span><\/h3>\n<p><span style=\"color: #000000;\">You can also use a different method to delete a row in a CSV file in Python using the <code>pandas<\/code> library, which can simplify the process. Here&#8217;s an example of how to do it with <code>pandas<\/code>:<\/span><\/p>\n<p><span style=\"color: #000000;\">First, you&#8217;ll need to install the <code>pandas<\/code> library if you haven&#8217;t already. You can install it using <code>pip<\/code>:<\/span><\/p>\n<blockquote>\n<pre><span style=\"color: #000000;\">\r\npip install pandas<\/span><\/pre>\n<\/blockquote>\n<p>&nbsp;<\/p>\n<p><span style=\"color: #000000;\">Now, you can use <code>pandas<\/code> to delete a row from a CSV file:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import pandas as pd\r\n\r\n# Specify the CSV file and the row index you want to delete\r\ncsv_file = 'example.csv'\r\nrow_index_to_delete = 2  # Replace with the index of the row you want to delete (0-based)\r\n\r\n# Read the CSV file into a DataFrame\r\ndf = pd.read_csv(csv_file)\r\n\r\n# Delete the specified row\r\ndf = df.drop(row_index_to_delete)\r\n\r\n# Write the DataFrame back to the CSV file without the deleted row\r\ndf.to_csv(csv_file, index=False)\r\n\r\nprint(f\"Row {row_index_to_delete} deleted from {csv_file}\")\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p><span style=\"color: #000000;\">This code uses the <code>pandas<\/code> library to read the CSV file into a DataFrame, delete the specified row, and then write the DataFrame back to the same CSV file without the deleted row. Replace <code>'example.csv'<\/code> with the path to your CSV file and set <code>row_index_to_delete<\/code> to the index of the row you want to delete (0-based index).<\/span><\/p>\n<p>&nbsp;<\/p>\n<h3><span style=\"color: #000000;\">Method-3<\/span><\/h3>\n<p><span style=\"color: #000000;\">There are multiple methods to delete a row from a CSV file in Python. In addition to the previously mentioned methods, here are a couple of alternative approaches:<\/span><\/p>\n<p><span style=\"color: #000000;\">Using <code>csv.DictReader<\/code> and <code>csv.DictWriter<\/code>:<\/span><\/p>\n<p>&nbsp;<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import csv\r\n\r\n# Specify the CSV file and the row index you want to delete\r\ncsv_file = 'example.csv'\r\nrow_index_to_delete = 2  # Replace with the index of the row you want to delete (0-based)\r\n\r\n# Read the CSV file and write the data excluding the specified row\r\nwith open(csv_file, 'r', newline='') as infile, open('temp.csv', 'w', newline='') as outfile:\r\n    reader = csv.DictReader(infile)\r\n    fieldnames = reader.fieldnames\r\n    writer = csv.DictWriter(outfile, fieldnames=fieldnames)\r\n    writer.writeheader()\r\n\r\n    for index, row in enumerate(reader):\r\n        if index != row_index_to_delete:\r\n            writer.writerow(row)\r\n\r\nimport os\r\nos.replace('temp.csv', csv_file)\r\nprint(f\"Row {row_index_to_delete} deleted from {csv_file}\")\r\n<\/pre>\n<p><span style=\"color: #000000;\">This code reads the CSV file using <code>csv.DictReader<\/code>, excludes the specified row, and then writes the data back to a temporary file. Finally, it replaces the original CSV file with the temporary file.<\/span><\/p>\n<h3><\/h3>\n<h3><span style=\"color: #000000;\">Method-4<\/span><\/h3>\n<p><span style=\"color: #000000;\">Using the <code>open()<\/code> function and <code>csv.writer<\/code>:<\/span><\/p>\n<p>&nbsp;<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import csv\r\n\r\n# Specify the CSV file and the row index you want to delete\r\ncsv_file = 'example.csv'\r\nrow_index_to_delete = 2  # Replace with the index of the row you want to delete (0-based)\r\n\r\n# Read the CSV file and write the data excluding the specified row\r\nwith open(csv_file, 'r', newline='') as infile, open('temp.csv', 'w', newline='') as outfile:\r\n    reader = csv.reader(infile)\r\n    writer = csv.writer(outfile)\r\n    for index, row in enumerate(reader):\r\n        if index != row_index_to_delete:\r\n            writer.writerow(row)\r\n\r\nimport os\r\nos.replace('temp.csv', csv_file)\r\nprint(f\"Row {row_index_to_delete} deleted from {csv_file}\")\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p><span style=\"color: #000000;\">This code uses the <code>open()<\/code> function to read and write the CSV file row by row, excluding the specified row, and then replaces the original CSV file with the temporary file.<\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python Program To Delete a Row in CSV File &nbsp; Method-1 You can delete a row in a CSV file in Python by reading the CSV file, excluding the row you want to delete, and then writing the remaining data back to the file. Here&#8217;s a Python program to do that: &nbsp; import csv # [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[16,20],"tags":[],"class_list":["post-4234","post","type-post","status-publish","format-standard","hentry","category-cbse-sample-papers-class-12","category-cbse-computer-science-with-python-class-12"],"_links":{"self":[{"href":"https:\/\/cbsepython.in\/wp-json\/wp\/v2\/posts\/4234","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/cbsepython.in\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cbsepython.in\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/cbsepython.in\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/cbsepython.in\/wp-json\/wp\/v2\/comments?post=4234"}],"version-history":[{"count":0,"href":"https:\/\/cbsepython.in\/wp-json\/wp\/v2\/posts\/4234\/revisions"}],"wp:attachment":[{"href":"https:\/\/cbsepython.in\/wp-json\/wp\/v2\/media?parent=4234"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cbsepython.in\/wp-json\/wp\/v2\/categories?post=4234"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cbsepython.in\/wp-json\/wp\/v2\/tags?post=4234"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}