class ExcelDocument():
  """
  Some convenience methods for Excel documents accessed
  through COM.
  """
 
  def __init__(self, visible=True):
    self.app = Dispatch("Excel.Application")
    self.app.Visible = visible
    self.sheet = 1
 
  def new(self, filename=None):
    """

    Create a new Excel workbook. If 'filename' specified,
    use the file as a template.
    """
    self.app.Workbooks.Add(filename)
 
  def open(self, filename):
    """
    Open an existing Excel workbook for editing.
    """
    self.app.Workbooks.Open(filename)

I am trying to manipulate excel files with pythin. The problem is that I have no control over the path of the files. By default, the path is "My Documents". I would like to change it to the path where the .py file is. For example, when I do

exc = ExcelDocument()
exc.open("some_file.xls")

It will open "some_file.xls" if there is one in "My Documents" otherwise it will display an error.

I am sure there is a way to overcome this. Does anyone know?

Thanks and Cheers!

There are two ways I know to do this:
1) Use an absolute path, ie instead of simply some_file.xls specify "C:/Documents and Settings/UserName/My Documents/some_file.xls" 2) Change the current working directory using os.chdir(desired_path) . You can also check your current working directory using os.get_cwd()

There are two ways I know to do this:
1) Use an absolute path, ie instead of simply some_file.xls specify "C:/Documents and Settings/UserName/My Documents/some_file.xls" 2) Change the current working directory using os.chdir(desired_path) . You can also check your current working directory using os.get_cwd()

Hi. Thanks a lot for your response. You gave me the tip I was looking for. os.getcwd() did the trick.

file_path = os.getcwd() + "\\some_file.xls"
exc.open(file_path)

Cheers.

Hi. Thanks a lot for your response. You gave me the tip I was looking for. os.getcwd() did the trick.

file_path = os.getcwd() + "\\some_file.xls"
exc.open(file_path)

Cheers.

As a tip: You don't need to use the + "\\ ... as you could use os.path.join(os.getcwd(), 'some_file.xls') . Although it's your preference... Just this way you don't need to worry about the escape/path characters.

Once again thanks. I did not know about that too.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.