0

I want to know whether it is possible to read the .csv file with specific row, after reading the row. I want to delete that specific row and update the .csv file with next row gets ascended. Assuming the .csv file has headers. If it is possible than how? Ex. below is my sample.csv

Time A B
12:25 5.6 4.5
12:30 1.2 -3.4
12:35 4.7 -4.0

Below is the code I have tried:

import csv
with open('sample.csv', 'rb') as inp, open('sample.csv', "a") as out:
    writer = csv.writer(out)
    for row in csv.reader(inp):
        writer.writerow(row)

But it gets, appended at the end of file. I have also tried to write it on the temporary file for intermediate stage. But, it still not serve my purpose cause I have to work on the same file. Here is the output sample.csv, which I want after one iteration of read:

Time A B
12:30 1.2 -3.4
12:35 4.7 -4.0
8
  • 1
    Yes it's possible, can you show your efforts Commented Aug 9, 2016 at 8:35
  • @EdChum I am new at python. I have gone through [basic links] (stackoverflow.com/questions/16020858/…). Implement that code could not serve my purpose. Commented Aug 9, 2016 at 8:39
  • As @EdChum said, please try something and post it here, we will guide you through. Commented Aug 9, 2016 at 8:41
  • @e-nouri I have edited my question. Commented Aug 9, 2016 at 8:57
  • 1
    It's on the accepted answer of the question you linked before. The last line, with the shutil code. Commented Aug 9, 2016 at 10:18

1 Answer 1

0

You could use StringIO to keep the contents in memory and then write them to the desired file at the end.

from io import StringIO
import csv

filename = 'sample.csv'
out_data = StringIO()

# Read CSV data to memory
with open(filename, 'r', newline='') as in_file:
    writer = csv.writer(out_data)
    for row in csv.reader(in_file):
        writer.writerow(row)

# Write intermediate data to file
with open(filename, 'w', newline='') as out_file:
    out_file.write(out_data.getvalue())

out_data.close()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.