-1

I am doing a school assignment where I have to take input from a user and save it to a text file. My file structure will be something like: - Customer register - Customer ID - .txt files 1-5

It can be saved in the python folder and I can make the folders like this:

os.makedirs("Customer register/Customer ID")

My question is, how do I set the path the text files are to be stored in, in the directory when I don't know the directory? So that no matter where the program is run it is saved in the "Customer ID" folder I create (but on the computer the program is run on)? Also, how do I make this work on both windows and mac?

I also want to program to be able to be executed several times, and check if the folder is there and save to the "Customer ID" folder if it already exists. Is there a way to do that?

EDIT: This is the code I am trying to use:

try:
    dirs = os.makedirs("Folder")
    path = os.getcwd()
    os.chdir(path + "/Folder")
    print (os.getcwd())
except:
    if os.path.exists:
        path = os.getcwd()
        unique_filename = str(uuid.uuid4())
        customerpath = os.getcwd()
        os.chdir(customerpath + "/Folder/" + unique_filename)

I am able to create a folder and change the directory (everything in "try" works as I want). When this folder is created I want to create a second folder with a random generated folder name (used for saving customer files). I can't get this to work in the same way. Error: FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\Users\48736\PycharmProjects\tina/Folder/979b9026-b2f6-4526-a17a-3b53384f60c4'

EDIT 2:

try:
    os.makedirs("Folder")
    path = os.getcwd()
    os.chdir(path + "/Folder")
    print (os.getcwd())

except:
    if os.path.exists:
        path = os.getcwd()
        os.chdir(os.path.join(path, 'Folder'))

print(os.getcwd())

def userId(folderid):
try:
    if not os.path.exists(folderid):
        os.makedirs(folderid)
except:
    if os.path.exists(folderid):
        os.chdir(path + "/Folder/" + folderid)
userId(str(uuid.uuid4()))


print(os.getcwd())

So I can now create a folder, change directory to the folder I have created and create a new folder with a unique filename within that folder. But I can't change the directory again to the folder with the unique filename. Any suggestions?

I have tried:

os.chdir(path + "/Folder/" + folderid)
os.chdir(path, 'Folder', folderid)
os.chdir(os.path.join(path, 'Folder', folderid))

But is still just stays in: C:\Users\47896\PycharmProjects\tina\Folder

  • 1
    Judging by your question you know that they need to store the files in `"Customer register/Customer ID"` so you can just prepend that to any files that you write. – Sasha Dec 17 '18 at 13:33
  • Alternatively, use `os.chdir` to set your working directory – L3viathan Dec 17 '18 at 13:37
  • If I got your problem correctly, `os.makedirs(customer_register + '/' + customer_id)`, fill the variables before call. To check if the folder is there you can use os.isdir('directory to check'). – Shariq Dec 17 '18 at 13:45
  • @TinaOlsen share the code you are approaching to solve this problem – sahasrara62 Dec 17 '18 at 15:32
  • @prashantrana its in my edit in the original post –  Dec 17 '18 at 22:15
  • @TinaOlsen use os.chdir(os.path.join(path ,'Folder')) not os.chdir(path + "/Folder") . – sahasrara62 Dec 17 '18 at 22:41

2 Answers2

1

You can use relative paths in your create directory command, i.e.

os.makedirs("./Customer register/Customer ID")

to create folder in project root (=where the primary caller is located) or

os.makedirs("../Customer register/Customer ID") in parent directory.

You can, of course, traverse the files tree as you need.

For specific options mentioned in your question, please, see makedirs documentation at Python 3 docs

  • I am able to make the directory I want, but I don't know how to set the current directory path to "any" computer. In other words, if you ran this program on your computer how do I get it to save to a wanted path on your computer? When I don't know your directory paths. –  Dec 17 '18 at 13:55
  • 1
    you should also note that using OS-dependent separators is a bad idea when we have `os.path.join` – Azat Ibrakov Dec 17 '18 at 13:56
  • 1
    @AzatIbrakov Python automatically substitutes valid path separator when usin `/` – Michal Polovka Dec 17 '18 at 14:17
  • @MichalPolovka Are you sure Python does that? According to what I know, Python passes the paths through to the OS. Luckily, Windows happily accepts `/` as well. Nevertheless, `os.path.join()` is good style. – glglgl Dec 17 '18 at 15:50
0

here is solution

import os
import shutil
import uuid

path_on_system = os.getcwd()  # directory where you want to     save data
path = r'Folder' # your working directory  

dir_path  = os.path.join(path_on_system, path)  


if not os.path.exists(dir_path):
    os.makedirs(dir_path)

file_name = str(uuid.uuid4())  # file which you have created 

if os.path.exists(file_name) and os.path.exists(dir_path):
    shutil.move(file_name,os.path.join(dir_path,file_name))
else:
      print(" {} does not exist".format(file_name))
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
  • The problem is that I dont know the full path to the directory because the program will be opened by my teacher on his computer. I know the full path on my computer, but I want this is work on any computer that runs the program. –  Dec 17 '18 at 13:52
  • @TinaOlsen See Mikulas's answer using relative paths – Michal Polovka Dec 17 '18 at 13:55
  • @TinaOlsen this will work . it will create 'Customer register/Customer ID' in the same directory where your program is running . – sahasrara62 Dec 17 '18 at 14:01
  • @MichalPolovka i find mikulas answer to create path using './' or '../' is wrong. you need to validate first the existence of that path . – sahasrara62 Dec 17 '18 at 14:08
  • I understand how to create the directory, I don't understand how to change the directory path to the directory I have created on a different computer. –  Dec 17 '18 at 14:08
  • @TinaOlsen i have updated solution, at path_on_system add the path where you want to save the data in your computer. – sahasrara62 Dec 17 '18 at 14:18
  • @prashantrana when I do this and then print (os.getcwd()) it still just shows the default pycharm folder path (example: C:\Users\48798\PycharmProjects\tina). Is there something else I am doing wrong? –  Dec 17 '18 at 14:44
  • @TinaOlsen can you tell me why you are using os.getcwd() . print (os.getcwd()) is giving you the path where your python file running . ie where you are executing the command. while creating file.txt python create it automatically in the folder where you are running your python file. – sahasrara62 Dec 17 '18 at 14:49
  • @prashantrana yes, so when I now create a new txt file is saves at C:\Users\48798\PycharmProjects\tina and not at C:\Users\48798\PycharmProjects\tina\home\user\myfoldername\Customerregister\CustomerID. I want to create the directory and then set my directory path to the directory created, so that text files created after this is saved to the new directory. –  Dec 17 '18 at 15:07
  • @TinaOlsen `\home\user\myfoldername` is just an example of the path where you want to store data intially . if you want to store at your location ie `C:\Users\48798\PycharmProjects\tina` change `path_on_system = os.getcwd()` this will create `Customer register/Customer ID` at `C:\Users\48798\PycharmProjects\tina ` as `C:\Users\48798\PycharmProjects\tina\Customer register/Customer ID` – sahasrara62 Dec 17 '18 at 15:19