Python Forum
Saving to a specific directory
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Saving to a specific directory
#1
Just wondering what the best way is to open and save the file to a directory I have called 'out'
C:\Users\blake\PycharmProjects\newb\out

renter = open("renter_"
                  + str(flname.get()) + "_"
                  + str(year) + "-"
                  + str(month) + "-"
                  + str(day), "w"
                  )
    renter.write("Employee: " + employee_dropdown.get())
    renter.write("\n")
Reply
#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
#3
how post in python forum
Reply


Forum Jump:

User Panel Messages

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