Python Forum
Saving to a specific directory
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Saving to a specific directory
#2
Use the modern API from pathlib.

Your path can be separated into different components:
  • Original: C:\Users\blake\PycharmProjects\newb\out
  • Path: C:\Users\blake\PycharmProjects\newb\
    File: out
  • Home: C:\Users\blake\
    Pycharm: PycharmProjects
    Project: newb
    File: out

from pathlib import Path

HOME = Path.home() # <-- this is dynamic. It depends on OS and logged-in User
PROJECTS = "PycharmProjects"
PROJECT = "newb"
FILE = "out"

# path objects support concatenation with /

complete_path_to_file = HOME / PROJECTS / PROJECT / FILE

# path objects to have the open() method, which replicates the built-in open()
with complete_path_to_file.open("w") as fd:
    fd.write("Hello World")
    print("Written data to", complete_path_to_file)


# but works also with the built-in open()
with open(complete_path_to_file, "w") as fd:
    fd.write("Hello World")
    print("Written data to", complete_path_to_file)
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
Saving to a specific directory - by blakefindlay - Jan-28-2021, 03:40 AM
RE: Saving to a specific directory - by DeaD_EyE - Jan-28-2021, 10:06 AM
RE: Saving to a specific directory - by Ron_Crafter - Jan-28-2021, 10:26 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020