-2

In my Python scripts, I write the specific path name. It will not work if I were to use it on another computer or folder.

ex: df = pd.read_csv('C:/VerySpecificNameForDocuments/test.csv', 'wb')

I have seen the use of: %/...

How can I re-write this to be usable in other computers/directories?

DasVisual
  • 779
  • 2
  • 7
  • 9
  • 5
    I don't think we have enough to answer this. What are your requirements? Will this file be provided by the user? Is there a working directory you can depend on being present? Can you provide a command-line option that tells the program where to find stuff? We don't know. –  May 12 '18 at 01:57
  • 1
    Thanks for the reply! I am looking to run my scripts on other computers and give them to others to use and I imagine their directories are different. For example: a script that organizes files will need to adapt to the person's directories. Yes, the files will be read from the user's computer. – DasVisual May 14 '18 at 00:40
  • If you have to handle different operating systems and filespecs you'll have to build than in as well. This is probably well out of scope for this question. –  May 14 '18 at 15:06

2 Answers2

0

If you don't want to hardcode a path on your scripts, environment variables are your friends, in python you can access them using os.environ, i.e.:

import os
# %USERPROFILE% environment variable  + "/documents" creates the path to `My documents` folder on windows systems
csv_file =  '{}\\documents\\file.csv'.format(os.environ['USERPROFILE'])
# C:\Users\Administrador\documents\file.csv
df = pd.read_csv(csv_file, 'wb')

Other interesting windows environment variables:

>>> import os
>>> os.environ['HOMEPATH']
'\\Users\\Administrador'
>>> os.environ['HOMEDRIVE']
'C:'
>>> os.environ['WINDIR']
'C:\\WINDOWS'
>>> os.environ['APPDATA']
'C:\\Users\\Administrador\\AppData\\Roaming'
>>>

PS:
If you need to support multiple OS's (linux, mac, windows), you may want to implement a simple OS detection function and deal with each system individually.

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
0

What you could do if you wanted is have a tkinter file selection window come up for the user. Here is the code:

import tkinter
import tkinter.filedialog #You might not need this line, sometimes I run into an error if I don't have it

tkinter.Tk().withdraw()
file = tkinter.filedialog.askopenfilename()

The "file" variable will have the full path with the file name.