create new folder in python with pathlib and write files into it

Bondrak picture Bondrak · Nov 27, 2017 · Viewed 59.7k times · Source

I'm doing something like this:

import pathlib

p = pathlib.Path("temp/").mkdir(parents=True, exist_ok=True)

with p.open("temp."+fn, "w", encoding ="utf-8") as f:
    f.write(result)

Error message: AttributeError: 'NoneType' object has no attribute 'open'

Obviously, based on the error message, mkdir returns None.

Jean-Francois Fabre suggested this correction:

p = pathlib.Path("temp/")
p.mkdir(parents=True, exist_ok=True)

with p.open("temp."+fn, "w", encoding ="utf-8") as f:
    ...

This triggered a new error message:

File "/Users/user/anaconda/lib/python3.6/pathlib.py", line 1164, in open opener=self._opener)
TypeError: an integer is required (got type str)

Answer

Till picture Till · Dec 5, 2017

You could try:

p = pathlib.Path("temp/")
p.mkdir(parents=True, exist_ok=True)
fn = "test.txt" # I don't know what is your fn
filepath = p / fn
with filepath.open("w", encoding ="utf-8") as f:
    f.write(result)

You shouldn't give a string as path. It is your object filepath which has the method open.

source