Kosig
Kosig

Reputation: 201

How to access through a path rather than just in current directory?

I have written a function which reads in an excel file and manipulates it. Obviously the .py file has to be in the same directory as the excel file. Is there a way to enter the path of the file so I can leave the script in the same place?

Upvotes: 0

Views: 1715

Answers (2)

Uku Loskit
Uku Loskit

Reputation: 42040

import os
os.chdir('/my/new/path')

You can change the current working directory by using os.chdir.

Another way would be to reference the excel file (however you are opening it) by an absolute path.

Upvotes: 4

John Machin
John Machin

Reputation: 82924

Obviously the .py file has to be in the same directory as the excel file.

I don't understand "obviously"

Is there a way to enter the path of the file so I can leave the script in the same place?

Yes, just type it in.

From the xlrd documentation:

open_workbook(filename=None, etc etc etc)

    Open a spreadsheet file for data extraction.

    filename
        The path to the spreadsheet file to be opened.

Snippet of script (presumes you are not hard-coding paths in your scripts):

import sys
import xlrd
book = xlrd.open_workbook(sys.argv[1])

Running this in a Windows "Command Prompt" window:

python c:\myscripts\demo_script.py d:\datafiles\foo.xls

Same principles apply to Linux, OS X, etc.

Also, this advice is quite independent of what software you are feeding the filename or filepath.

About hard-coding file paths in Python scripts on Windows:

In ascending order of preferability:

  • Use backslashes: "c:\testdata\new.xls" ... the \t will be interpreted as a TAB character. The \n will be interpreted as a newline. Fail.

  • Escape your backslashes: "c:\\testdata\\new.xls" ... Yuk.

  • Use a raw string: r"c:\testdata\new.xls"

  • Use forward slashes: "c:/testdata/new.xls" ... yes, it works, when fed to open().

  • Don't do it ... see script example above.

Upvotes: 2

Related Questions