Reputation: 4198
I am trying to create a file, but in different directory. For example, when my app is in /home/app1
I would like to create a file in /home/logs
I was trying something like this:
json_file = "%s.json" % json_name
json_file_path = pathlib.Path("%s/%s" % (path, json_file))
if not json_file_path.is_file():
file = open(json_file_path, 'w+')
file.close()
else:
print("NotMkay")
Where path is /home/logs
, json_file is filename "example.json" and json_file_path is path + json_file
But all I'm getting is:
TypeError: invalid file: PosixPath
Upvotes: 0
Views: 211
Reputation: 244
Use os.path.join for joining path and os.path exists for checking. String formatting is not safe way. Working example
import os.path
json_file = "%s.json" % 'tst.json'
json_file_path = os.path.join('~', json_file)
print(os.path.exists(json_file_path))
This will print 'False'. For creating dirtree you can use:
os.makedirs(json_file_path)
Upvotes: 0
Reputation: 76194
file = open(json_file_path, 'w+')
I don't think you can pass a Path
object as an argument to open
. Instead, try
file = json_file_path.open('w+')
Upvotes: 2