DECROMAX

Save file, make directory if not exists

Feb 14th, 2022
305
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.38 KB | None | 0 0
  1. # writes file to filepath, creates dir if does not exist
  2. from pathlib import Path
  3.  
  4. path = Path("/your/file/path/name_of_dir") # path of dir
  5. path.mkdir(parents=True, exist_ok=True)  # cretes dir if not exist
  6.  
  7. file = "name_of_file.txt"  # file name
  8.  
  9. filepath = path / file  # joins path and file
  10.  
  11. with open(filepath, "w") as f:
  12.     f.write("This is an example file")
  13.     f.close()
Advertisement
Add Comment
Please, Sign In to add comment