How to get an absolute file path in Python

0 votes

Given a path such as "mydir/myfile.txt", how do I find the file's absolute path relative to the current working directory in Python? E.g. on Windows, I might end up with:

"C:/example/cwd/mydir/myfile.txt"
Dec 7, 2020 in Python by kartik
• 37,520 points
796 views

1 answer to this question.

0 votes

Hello @kartik,

Try this out:

>>> import os
>>> os.path.abspath("mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'

Also works if it is already an absolute path:

>>> import os
>>> os.path.abspath("C:/example/cwd/mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'
answered Dec 7, 2020 by Niroj
• 82,880 points

Related Questions In Python

0 votes
1 answer

How to get absolute path in python?

Instead of using os.path.dirname method which returns the relative ...READ MORE

answered Feb 4, 2019 in Python by Omkar
• 69,220 points
7,815 views
0 votes
1 answer

How to get path with filename in python?

There is no direct way to get ...READ MORE

answered Feb 4, 2019 in Python by Omkar
• 69,220 points
3,550 views
0 votes
0 answers
0 votes
1 answer

I want to download a file from the website by web scraping. Can anyone explain how to do this in jupyter lab (python) with an example?

Hey, Web scraping is a technique to automatically ...READ MORE

answered Apr 7, 2020 in Python by Gitika
• 65,890 points
2,359 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,397 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,004 views
0 votes
1 answer

How to get the latest file in a folder using python?

Hello @kartik,  would suggest using glob.iglob() instead of the glob.glob(), as ...READ MORE

answered May 27, 2020 in Python by Niroj
• 82,880 points
11,492 views
0 votes
1 answer

How to reimport an updated package while in Python Interpreter?

Hello, To import an updated package while in ...READ MORE

answered May 12, 2020 in Python by Niroj
• 82,880 points
2,521 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP