开发者

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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜