Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use pathlib & csv module to write?

Tags:

python

file

csv

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
like image 292
Qiulang 邱朗 Avatar asked Oct 29 '25 14:10

Qiulang 邱朗


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)
like image 165
blhsing Avatar answered Oct 31 '25 04:10

blhsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!