How do I use pathlib & csv module to write?

Viewed 2298

I use csv module to create a csv file. If I use build-in open function, the code is like this

import csv
...
csvFileObj = open(file.name, 'w')
csvWriter = csv.writer(csvFileObj)

But I don't know how to do that with pathlib, if I use the code like this

import csv
from pathlib import Path
...
csvFileObj = Path.cwd() / file.name
csvFileObj.open("w", encoding="utf-8")
csvWriter = csv.writer(csvFileObj)

I got the error

csvWriter = csv.writer(csvFileObj)
TypeError: argument 1 must have a "write" method
1 Answers

csvFileObj is a Path object. You should pass to csv.writer a file object instead:

with csvFileObj.open("w", encoding="utf-8") as file:
    csvWriter = csv.writer(file)
Related