Can I modify a CSV file inline using Python's CSV library, or similar technique?
Current I am processing a file and updating the first column (a name field) to change the formatting. A simplified version of my code looks like this:
with open('tmpEmployeeDatabase-out.csv', 'w') as csvOutput: writer = csv.writer(csvOutput, delimiter=',', quotechar='"') with open('tmpEmployeeDatabase.csv', 'r') as csvFile: reader = csv.reader(csvFile, delimiter=',', quotechar='"') for row in reader: row[0] = row[0].title() writer.writerow(row)
The philosophy works, but I am curious if I can do an inline edit so that I'm not duplicating the file.
I've tried the follow, but this appends the new records to the end of the file instead of replacing them.
with open('tmpEmployeeDatabase.csv', 'r+') as csvFile: reader = csv.reader(csvFile, delimiter=',', quotechar='"') writer = csv.writer(csvFile, delimiter=',', quotechar='"') for row in reader: row[1] = row[1].title() writer.writerow(row)
Steps for writing a CSV file First, open the CSV file for writing ( w mode) by using the open() function. Second, create a CSV writer object by calling the writer() function of the csv module. Third, write data to CSV file by calling the writerow() or writerows() method of the CSV writer object.
Step 1: Load the CSV file using the open method in a file object. Step 2: Create a reader object with the help of DictReader method using fileobject. This reader object is also known as an iterator can be used to fetch row-wise data. Step 3: Use for loop on reader object to get each row.
No, you should not attempt to write to the file you are currently reading from. You can do it if you keep seek
ing back after reading a row but it is not advisable, especially if you are writing back more data than you read.
The canonical method is to write to a new, temporary file and move that into place over the old file you read from.
from tempfile import NamedTemporaryFile import shutil import csv filename = 'tmpEmployeeDatabase.csv' tempfile = NamedTemporaryFile('w+t', newline='', delete=False) with open(filename, 'r', newline='') as csvFile, tempfile: reader = csv.reader(csvFile, delimiter=',', quotechar='"') writer = csv.writer(tempfile, delimiter=',', quotechar='"') for row in reader: row[1] = row[1].title() writer.writerow(row) shutil.move(tempfile.name, filename)
I've made use of the tempfile
and shutil
libraries here to make the task easier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With