开发者

using CSV module with readline()

Yesterday I posted the below link: Python CSV Module read and write simultaneously

Several people suggested that I "If file b is not extremely large I would suggest using readlines() to get a list of all lines and then iterate over the list and change lines as needed."

I want to still be able to use the functionality of the CSV Module but do what they have suggested. I am new to python and still don't quite undertand how I should do this.

Could someone please provide me with an example of开发者_C百科 how I should do this.


Here is a sample that reads a CSV file using a DictReader and uses a DictWriter to write to stdout. The file has a column named PERCENT_CORRECT_FLAG, and this modifies the CSV file to set this field to 0.

#!/usr/bin/env python
from __future__ import with_statement
from __future__ import print_function

from csv import DictReader, DictWriter
import sys

def modify_csv(filename):
    with open(filename) as f:
        reader = DictReader(f)
        writer = DictWriter(sys.stdout, fieldnames=reader.fieldnames)
        for i, s in enumerate(writer.fieldnames):
            print(i, s, file=sys.stdout)
        for row in reader:
            row['PERCENT_CORRECT_FLAG'] = '0'
            writer.writerow(row)

if __name__ == '__main__':
    for filename in sys.argv[1:]:
        modify_csv(filename)

If you do not want to write to stdout, you can open another file for write and use that. Note that if you want to write back to the original file, you have to either:

  1. Read the file into memory and close the file before opening for write or

  2. Open a file with a different name for write and rename it after closing it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜