Ryan Reid
Ryan Reid

Reputation: 41

How do you automatically find the file path in python

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

Upvotes: 1

Views: 3879

Answers (4)

abc
abc

Reputation: 11929

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')

Upvotes: 4

exiz
exiz

Reputation: 93

This will give you the full path where the script is

import os
path = os.path.dirname(os.path.realpath(__file__))

Upvotes: 0

Walklikeapenguin
Walklikeapenguin

Reputation: 137

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!

Upvotes: 1

nvi
nvi

Reputation: 63

The os module is what you're looking for.

import os
os.getcwd()

Upvotes: 1

Related Questions