1

I am looking to parse an excel data file and would like to make it so that my program automatically fills out the file path based on the file location of the current python file I am using.

For example, in the code

categorization_file = r'C:\Users\Name\Desktop\ExcelFile.xlsx'
inputVariables = categorization_file.parse(sheet_name='Control')

I would like the "r'C:\Users\Name\Desktop\" part to be automatically generated if possible. This path will be common with the file I am running my program from.

Thanks

Stop harming Monica
  • 12,141
  • 1
  • 36
  • 56
Ryan Reid
  • 41
  • 1
  • 10

4 Answers4

4
import os
# to get the location of the current python file
basedir = os.path.dirname(os.path.abspath(__file__))
# to join it with the filename
categorization_file = os.path.join(basedir,'ExcelFile.xlsx')
abc
  • 11,579
  • 2
  • 26
  • 51
1

The os module is what you're looking for.

import os
os.getcwd()
nvi
  • 63
  • 7
1

Use os.path.dirname like this:

import os

base_dir = os.path.dirname('C:\Users\Name\Desktop\ExcelFile.xlsx')

or even better:

import os

filepath = 'C:\Users\Name\Desktop\ExcelFile.xlsx'
base_dir = os.path.dirname(filepath)

In both cases, base_dir will now evaluate to 'C:\Users\Name\Desktop\'

Hope this helps!

Walklikeapenguin
  • 127
  • 2
  • 10
0

This will give you the full path where the script is

import os
path = os.path.dirname(os.path.realpath(__file__))
exiz
  • 93
  • 6