How to get parent dir in python
https://stackoverflow.com/questions/2817264/how-to-get-the-parent-dir-location
How to get the parent dir location
2014-05-07
Zjm
<div><div>
 
<div>
 
 
<div>
 
 <div>
 
<p>this code is get the templates/blog1/page.html in b.py:</p>
<pre><code>path = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'blog1/page.html'))
</code></pre>
<p>but i want to get the parent dir location:</p>
<pre><code>aParent
 |--a
 | |---b.py
 | |---templates
 | |--------blog1
 | |-------page.html
 |--templates
 |--------blog1
 |-------page.html
</code></pre>
<p>and how to get the aParent location</p>
<p>thanks</p>
<p><strong>updated:</strong></p>
<p>this is right:</p>
<pre><code>dirname=os.path.dirname
path = os.path.join(dirname(dirname(__file__)), os.path.join('templates', 'blog1/page.html'))
</code></pre>
<p>or </p>
<pre><code>path = os.path.abspath(os.path.join(os.path.dirname(__file__),".."))
</code></pre>
 </div>
 
 <div>
 
 <div>
 
 <div>
 <a href="/users/1843331/tim"><p></p></a>
 </div>
 <div>
 <p><a href="/users/1843331/tim">Tim</a></p><p>41.2k18 gold badges129 silver badges143 bronze badges
 </p>
 </div>
</div>
 <div>
 <p>
 asked May 12, 2010 at 8:57
 </p>
 <div>
 <a href="/users/234322/zjm1126"><p></p></a>
 </div>
 
</div>
 </div>
 
</div>
 <p>6</p>
 </div>
 <div>
 
 
<div>
 
 
<div>
 
 <p>You can apply dirname repeatedly to climb higher: <code>dirname(dirname(file))</code>. This can only go as far as the root package, however. If this is a problem, use <code>os.path.abspath</code>: <code>dirname(dirname(abspath(file)))</code>.</p>
 <div>
 <p>
 answered May 12, 2010 at 9:03
 </p>
 <div>
 <a href="/users/9990/marcelo-cantos"><p></p></a>
 </div>
 <div>
 <p><a href="/users/9990/marcelo-cantos">Marcelo Cantos</a>Marcelo Cantos</p><p>179k38 gold badges324 silver badges363 bronze badges
 </p>
 </div>
</div>
 
</div>
 <p>4</p>
 </div>
 
<div>
 
 
<div>
 
 <div>
<p>Use <strong>relative path</strong> with the <a href="https://docs.python.org/3/library/pathlib.html"><code>pathlib</code></a> module in Python 3.4+:</p>
<pre><code>from pathlib import Path
Path(__file__).parent
</code></pre>
<p>You can use multiple calls to <code>parent</code> to go further in the path:</p>
<pre><code>Path(__file__).parent.parent
</code></pre>
<p>As an alternative to specifying <code>parent</code> twice, you can use:</p>
<pre><code>Path(__file__).parents[1]
</code></pre>
 </div>
 <div>
 <p>
 answered Sep 21, 2016 at 13:18
 </p>
 <div>
 <a href="/users/5770004/gavriel-cohen"><p></p></a>
 </div>
 
</div>
 
</div>
 <p>3</p>
 </div>
 
<div>
 
 
<div>
 
 <div>
<p><code>os.path.abspath</code> doesn't validate anything, so if we're already appending strings to <code>__file__</code> there's no need to bother with <code>dirname</code> or joining or any of that. Just treat <code>__file__</code> as a directory and start climbing:</p>
<pre><code># climb to __file__'s parent's parent:
os.path.abspath(__file__ + "/../../")
</code></pre>
<p>That's far less convoluted than <code>os.path.abspath(os.path.join(os.path.dirname(__file__),".."))</code> and about as manageable as <code>dirname(dirname(__file__))</code>. Climbing more than two levels starts to get ridiculous.</p>
<p>But, since we know how many levels to climb, we could clean this up with a simple little function:</p>
<pre><code>uppath = lambda _path, n: os.sep.join(_path.split(os.sep)[:-n])
# __file__ = "/aParent/templates/blog1/page.html"
&gt;&gt;&gt; uppath(__file__, 1)
'/aParent/templates/blog1'
&gt;&gt;&gt; uppath(__file__, 2)
'/aParent/templates'
&gt;&gt;&gt; uppath(__file__, 3)
'/aParent'
</code></pre>
 </div>
 <div>
 <p>
 answered Jan 4, 2013 at 3:38
 </p>
 <div>
 <a href="/users/503463/joemaller"><p></p></a>
 </div>
 <div>
 <p><a href="/users/503463/joemaller">joemaller</a>joemaller</p><p>19.2k7 gold badges66 silver badges83 bronze badges
 </p>
 </div>
</div>
 
</div>
 <p>2</p>
 </div>
 
<div>
 
 
<div>
 
 <div>
<pre><code>os.path.dirname(os.path.abspath(__file__))
</code></pre>
<p>Should give you the path to <code>a</code>.</p>
<p>But if <code>b.py</code> is the file that is currently executed, then you can achieve the same by just doing</p>
<pre><code>os.path.abspath(os.path.join('templates', 'blog1', 'page.html'))
</code></pre>
 </div>
 <div>
 <p>
 answered May 12, 2010 at 9:36
 </p>
 <div>
 <a href="/users/218196/felix-kling"><p></p></a>
 </div>
 <div>
 <p><a href="/users/218196/felix-kling">Felix Kling</a>Felix Kling</p><p>784k173 gold badges1083 silver badges1131 bronze badges
 </p>
 </div>
</div>
 
</div>
 <p>2</p>
 </div>
 
<div>
 
 <div>
<p><code>os.pardir</code> is a better way for <code>../</code> and more readable. </p>
<pre><code>import os
print os.path.abspath(os.path.join(given_path, os.pardir)) 
</code></pre>
<p>This will return the parent path of the given_path</p>
 </div>
 <div>
 <p>
 answered Nov 25, 2013 at 14:32
 </p>
 <div>
 <a href="/users/47441/sun-liwen"><p></p></a>
 </div>
 <div>
 <p><a href="/users/47441/sun-liwen">Sun Liwen</a>Sun Liwen</p><p>1,2241 gold badge15 silver badges21 bronze badges
 </p>
 </div>
</div>
 
</div>
 
<div>
 
 
<div>
 
 <div>
<p>A simple way can be:</p>
<pre><code>import os
current_dir = os.path.abspath(os.path.dirname(__file__))
parent_dir = os.path.abspath(current_dir + "/../")
print parent_dir
</code></pre>
 </div>
 <div>
 <p>
 answered Aug 7, 2013 at 21:59
 </p>
 <div>
 <a href="/users/1827801/muneeb-ali"><p></p></a>
 </div>
 <div>
 <p><a href="/users/1827801/muneeb-ali">Muneeb Ali</a>Muneeb Ali</p><p>2,0161 gold badge16 silver badges8 bronze badges
 </p>
 </div>
</div>
 
</div>
 <p>0</p>
 </div>
 
<div>
 
 
<div>
 
 <div>
<p>May be join two <code>..</code> folder, to get parent of the parent folder?</p>
<pre><code>path = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),"..",".."))
</code></pre>
 </div>
 <div>
 <p>
 answered May 12, 2010 at 9:26
 </p>
 <div>
 <a href="/users/213464/you"><p></p></a>
 </div>
 <div>
 <p><a href="/users/213464/you">YOU</a>YOU</p><p>118k34 gold badges186 silver badges218 bronze badges
 </p>
 </div>
</div>
 
</div>
 <p>0</p>
 </div>
 
<div>
 
 <div>
<p>Here is another relatively simple solution that:</p>
<ul>
<li>does not use <code>dirname()</code> (which does not work as expected on one level arguments like "file.txt" or relative parents like "..")</li>
<li>does not use <code>abspath()</code> (avoiding any assumptions about the current working directory) but instead preserves the relative character of paths</li>
</ul>
<p>it just uses <code>normpath</code> and <code>join</code>:</p>
<pre><code>def parent(p):
 return os.path.normpath(os.path.join(p, os.path.pardir))
# Example:
for p in ['foo', 'foo/bar/baz', 'with/trailing/slash/', 
 'dir/file.txt', '../up/', '/abs/path']:
 print parent(p)
</code></pre>
<p>Result:</p>
<pre><code>.
foo/bar
with/trailing
dir
..
/abs
</code></pre>
 </div>
 <div>
 <p>
 answered Mar 19, 2014 at 16:03
 </p>
 <div>
 <a href="/users/1303398/stefaan"><p></p></a>
 </div>
 <div>
 <p><a href="/users/1303398/stefaan">Stefaan</a>Stefaan</p><p>4,6663 gold badges22 silver badges16 bronze badges
 </p>
 </div>
</div>
 
</div>
 
<div>
 
 <div>
<p>Use the following to jump to previous folder:</p>
<pre><code>os.chdir(os.pardir)
</code></pre>
<p>If you need multiple jumps a good and easy solution will be to use a simple decorator in this case.</p>
 </div>
 <div>
 
 <div>
 
 <div>
 <a href="/users/1454176/zulu"><p></p></a>
 </div>
 <div>
 <p><a href="/users/1454176/zulu">Zulu</a></p><p>8,4089 gold badges47 silver badges56 bronze badges
 </p>
 </div>
</div>
 <div>
 <p>
 answered Apr 3, 2015 at 21:22
 </p>
 <div>
 <a href="/users/4747770/marco-smdm"><p></p></a>
 </div>
 <div>
 <p><a href="/users/4747770/marco-smdm">Marco smdm</a>Marco smdm</p><p>1,0101 gold badge15 silver badges25 bronze badges
 </p>
 </div>
</div>
 </div>
 
</div>
 
<div>
 
 
<div>
 
 <p>
from os.path import basename, dirname<br />
basename(dirname('foo/bar/foo_bar'))
 </p>
 <div>
 <p>
 answered Apr 3, 2022 at 18:53
 </p>
 <div>
 <a href="/users/18694330/ernest"><p></p></a>
 </div>
 
</div>
 
</div>
 <p>1</p>
 </div>
 
<div>
 
 
<div>
 
 <div>
<p>I think use this is better:</p>
<pre><code>os.path.realpath(__file__).rsplit('/', X)[0]
In [1]: __file__ = "/aParent/templates/blog1/page.html"
In [2]: os.path.realpath(__file__).rsplit('/', 3)[0]
Out[3]: '/aParent'
In [4]: __file__ = "/aParent/templates/blog1/page.html"
In [5]: os.path.realpath(__file__).rsplit('/', 1)[0]
Out[6]: '/aParent/templates/blog1'
In [7]: os.path.realpath(__file__).rsplit('/', 2)[0]
Out[8]: '/aParent/templates'
In [9]: os.path.realpath(__file__).rsplit('/', 3)[0]
Out[10]: '/aParent'
</code></pre>
 </div>
 <div>
 <p>
 answered Feb 15, 2014 at 15:39
 </p>
 <div>
 <a href="/users/2202409/dongweiming"><p></p></a>
 </div>
 <div>
 <p><a href="/users/2202409/dongweiming">dongweiming</a>dongweiming</p><p>8131 gold badge8 silver badges7 bronze badges
 </p>
 </div>
</div>
 
</div>
 <p>1</p>
 </div>
 
<div>
 
 <div>
<p>I tried: </p>
<pre><code>import os
os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), os.pardir))
</code></pre>
 </div>
 <div>
 <p>
 answered May 7, 2014 at 6:03
 </p>
 <div>
 <a href="/users/260826/gogasca"><p></p></a>
 </div>
 <div>
 <p><a href="/users/260826/gogasca">gogasca</a>gogasca</p><p>8,9445 gold badges77 silver badges120 bronze badges
 </p>
 </div>
</div>
 
</div>
 
 <h2>
 
 </h2>
 </div>
 </div>||||I|||| Stack Overflow
 1. About
 2. Products
 3. For Teams
 1. Stack Overflow Public questions & answers
 2. Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
 3. Talent Build your employer brand
 4. Advertising Reach developers & technologists worldwide
 5. About the company
 Loading…

 1. current community

 + Stack Overflow
 help chat
 + Meta Stack Overflow

 your communities

 Sign up or log in to customize your list.

 more stack exchange communities

 company blog
 2. 
 3. Log in
 4. Sign up
 1. Home
 2. 
 1. Public
 2. Questions
 3. Tags
 4. Users
 5. Companies
 6. Collectives
 7. Explore Collectives
 3. 
 1. Teams
 Stack Overflow for Teams – Start collaborating and sharing organizational knowledge. Create a free Team Why Teams?
 2. Teams
 3. Create free Team

 Collectives™ on Stack Overflow

 Find centralized, trusted content and collaborate around the technologies you use most.

 Learn more about Collectives

 Teams

 Q&A for work

 Connect and share knowledge within a single location that is structured and easy to search.

 Learn more about Teams

 How to get the parent dir location

 Ask Question
 Asked 12 years, 9 months ago
 Modified 10 months ago
 Viewed 232k times
 165

 this code is get the templates/blog1/page.html in b.py:

 path = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'blog1/page.html'))
 

 but i want to get the parent dir location:

 aParent
 |--a
 | |---b.py
 | |---templates
 | |--------blog1
 | |-------page.html
 |--templates
 |--------blog1
 |-------page.html
 

 and how to get the aParent location

 thanks

 updated:

 this is right:

 dirname=os.path.dirname
 path = os.path.join(dirname(dirname(__file__)), os.path.join('templates', 'blog1/page.html'))
 

 or

 path = os.path.abspath(os.path.join(os.path.dirname(__file__),".."))
 
 * python
 * path
 Share
 Improve this question
 Follow
 edited May 7, 2014 at 6:06
 Tim
 41.2k 18 18 gold badges 129 129 silver badges 143 143 bronze badges
 asked May 12, 2010 at 8:57
 zjm1126 zjm1126
 61.9k 77 77 gold badges 173 173 silver badges 219 219 bronze badges
 6
 * 2
 So you want to get blog1 or a ? And where is your current file located?
 – Felix Kling
 May 12, 2010 at 9:03
 * do you understand what your code is doing?
 – SilentGhost
 May 12, 2010 at 9:07
 * 2
 yes , it get the templates/blog1/page.html
 – zjm1126
 May 12, 2010 at 9:09
 * os.path.join('templates', 'blog1/page.html') looks strange to me. You are mixing things up. Either os.path.join('templates', 'blog1', 'page.html') or 'templates/blog1/page.html' . And much easier would be os.path.abspath(os.path.join('templates', 'blog1', 'page.html')) then
 – Felix Kling
 May 12, 2010 at 9:15
 * 1
 @zjm: no, you don't get that page. It's not some blackbox that you could just use to get the template file. It performs a series of trivial small steps, and if you could understand them, you wouldn't have this question.
 – SilentGhost
 May 12, 2010 at 9:20
 | Show 1 more comment

 12 Answers

 Sorted by: Reset to default
 Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first)
 216

 You can apply dirname repeatedly to climb higher: dirname(dirname(file)). This can only go as far as the root package, however. If this is a problem, use os.path.abspath: dirname(dirname(abspath(file))).

 Share
 Improve this answer
 Follow
 edited Feb 1, 2014 at 1:11
 answered May 12, 2010 at 9:03
 Marcelo Cantos Marcelo Cantos
 179k 38 38 gold badges 324 324 silver badges 363 363 bronze badges
 4
 * 43
 I know the OP knows about dirname . It isn't obvious to everyone that applying dirname to a directory yields the parent directory.
 – Marcelo Cantos
 May 12, 2010 at 9:09
 * 6
 dirname does NOT always return the parent directory; twitter.com/#!/ActiveState/status/671049326788608
 – Sridhar Ratnakumar
 Nov 5, 2010 at 22:12
 * 2
 @Sridhar: That depends on your perspective; I consider a path ending in / as not representing the leaf directory entry itself, but its contents, which is why, e.g., mv xxx yyy/ fails if yyy isn't a preexisting directory. In any case, even if we take your point as a given, it is irrelevant in the context of my answer. Neither file nor the result of dirname will ever end in a / .
 – Marcelo Cantos
 Nov 6, 2010 at 0:56
 * 1
 Minor correction: dirname may return '/' , which clearly ends in a / . That is the only exception, AFAIK.
 – Marcelo Cantos
 Feb 6, 2013 at 23:19
 Add a comment |
 70

 Use relative path with the pathlib module in Python 3.4+:

 from pathlib import Path
 
 Path(__file__).parent
 

 You can use multiple calls to parent to go further in the path:

 Path(__file__).parent.parent
 

 As an alternative to specifying parent twice, you can use:

 Path(__file__).parents[1]
 
 Share
 Improve this answer
 Follow
 edited Aug 26, 2019 at 6:44
 answered Sep 21, 2016 at 13:18
 Gavriel Cohen Gavriel Cohen
 4,219 33 33 silver badges 39 39 bronze badges
 3
 * 2
 If you need the path as a string because you want to modify it, you can just use str(Path(__file__).parent) .
 – Philipp
 May 10, 2020 at 11:16
 * 3
 It seems that in python 3.8.5 you need Path(__file__).resolve().parent
 – Markus Kaukonen
 Dec 22, 2020 at 8:41
 * 2
 Thanks, I knew about .parent but not about .parents . IMO, that's much nicer than chaining .parent or os.path.dirname s.
 – hkennyv
 Mar 15, 2021 at 17:44
 Add a comment |
 68

 os.path.abspath doesn't validate anything, so if we're already appending strings to __file__ there's no need to bother with dirname or joining or any of that. Just treat __file__ as a directory and start climbing:

 # climb to __file__'s parent's parent:
 os.path.abspath(__file__ + "/../../")
 

 That's far less convoluted than os.path.abspath(os.path.join(os.path.dirname(__file__),"..")) and about as manageable as dirname(dirname(__file__)). Climbing more than two levels starts to get ridiculous.

 But, since we know how many levels to climb, we could clean this up with a simple little function:

 uppath = lambda _path, n: os.sep.join(_path.split(os.sep)[:-n])
 
 # __file__ = "/aParent/templates/blog1/page.html"
 >>> uppath(__file__, 1)
 '/aParent/templates/blog1'
 >>> uppath(__file__, 2)
 '/aParent/templates'
 >>> uppath(__file__, 3)
 '/aParent'
 
 Share
 Improve this answer
 Follow
 answered Jan 4, 2013 at 3:38
 joemaller joemaller
 19.2k 7 7 gold badges 66 66 silver badges 83 83 bronze badges
 2
 * 3
 This is nice, but it would also be cool if the standard library added a convenience function that accomplished this...don't want to come to SO every time I need this func
 – gradi3nt
 Jan 27, 2016 at 17:26
 * 6
 Would os.path.abspath(os.path.join(__file__, "..", "..") be more portable?
 – slowD
 Aug 31, 2018 at 0:28
 Add a comment |
 13
 os.path.dirname(os.path.abspath(__file__))
 

 Should give you the path to a.

 But if b.py is the file that is currently executed, then you can achieve the same by just doing

 os.path.abspath(os.path.join('templates', 'blog1', 'page.html'))
 
 Share
 Improve this answer
 Follow
 answered May 12, 2010 at 9:36
 Felix Kling Felix Kling
 784k 173 173 gold badges 1083 1083 silver badges 1131 1131 bronze badges
 2
 * 1
 o ,i know ,you are right ,and i want to get the a's parent folder. how to get it
 – zjm1126
 May 12, 2010 at 9:43
 * @zjm1126: See Marcelo Cantos' answer. Apply dirname() twice. Everything you need now should be on this site.
 – Felix Kling
 May 12, 2010 at 9:51
 Add a comment |
 9

 os.pardir is a better way for ../ and more readable.

 import os
 print os.path.abspath(os.path.join(given_path, os.pardir)) 
 

 This will return the parent path of the given_path

 Share
 Improve this answer
 Follow
 answered Nov 25, 2013 at 14:32
 Sun Liwen Sun Liwen
 1,224 1 1 gold badge 15 15 silver badges 21 21 bronze badges
 Add a comment |
 6

 A simple way can be:

 import os
 current_dir = os.path.abspath(os.path.dirname(__file__))
 parent_dir = os.path.abspath(current_dir + "/../")
 print parent_dir
 
 Share
 Improve this answer
 Follow
 answered Aug 7, 2013 at 21:59
 Muneeb Ali Muneeb Ali
 2,016 1 1 gold badge 16 16 silver badges 8 8 bronze badges
 0
 Add a comment |
 3

 May be join two .. folder, to get parent of the parent folder?

 path = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),"..",".."))
 
 Share
 Improve this answer
 Follow
 answered May 12, 2010 at 9:26
 YOU YOU
 118k 34 34 gold badges 186 186 silver badges 218 218 bronze badges
 0
 Add a comment |
 2

 Here is another relatively simple solution that:

 * does not use dirname() (which does not work as expected on one level arguments like "file.txt" or relative parents like "..")
 * does not use abspath() (avoiding any assumptions about the current working directory) but instead preserves the relative character of paths

 it just uses normpath and join:

 def parent(p):
 return os.path.normpath(os.path.join(p, os.path.pardir))
 
 # Example:
 for p in ['foo', 'foo/bar/baz', 'with/trailing/slash/', 
 'dir/file.txt', '../up/', '/abs/path']:
 print parent(p)
 

 Result:

 .
 foo/bar
 with/trailing
 dir
 ..
 /abs
 
 Share
 Improve this answer
 Follow
 answered Mar 19, 2014 at 16:03
 Stefaan Stefaan
 4,666 3 3 gold badges 22 22 silver badges 16 16 bronze badges
 Add a comment |
 2

 Use the following to jump to previous folder:

 os.chdir(os.pardir)
 

 If you need multiple jumps a good and easy solution will be to use a simple decorator in this case.

 Share
 Improve this answer
 Follow
 edited Apr 4, 2015 at 0:12
 Zulu
 8,408 9 9 gold badges 47 47 silver badges 56 56 bronze badges
 answered Apr 3, 2015 at 21:22
 Marco smdm Marco smdm
 1,010 1 1 gold badge 15 15 silver badges 25 25 bronze badges
 Add a comment |
 1
 from os.path import basename, dirname
 basename(dirname('foo/bar/foo_bar'))
 Share
 Improve this answer
 Follow
 answered Apr 3, 2022 at 18:53
 Ernest Ernest
 11 1 1 bronze badge
 1
 * 1
 Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center .
 – Community Bot
 Apr 3, 2022 at 21:54
 Add a comment |
 0

 I think use this is better:

 os.path.realpath(__file__).rsplit('/', X)[0]
 
 
 In [1]: __file__ = "/aParent/templates/blog1/page.html"
 
 In [2]: os.path.realpath(__file__).rsplit('/', 3)[0]
 Out[3]: '/aParent'
 
 In [4]: __file__ = "/aParent/templates/blog1/page.html"
 
 In [5]: os.path.realpath(__file__).rsplit('/', 1)[0]
 Out[6]: '/aParent/templates/blog1'
 
 In [7]: os.path.realpath(__file__).rsplit('/', 2)[0]
 Out[8]: '/aParent/templates'
 
 In [9]: os.path.realpath(__file__).rsplit('/', 3)[0]
 Out[10]: '/aParent'
 
 Share
 Improve this answer
 Follow
 answered Feb 15, 2014 at 15:39
 dongweiming dongweiming
 813 1 1 gold badge 8 8 silver badges 7 7 bronze badges
 1
 * Not quite, it's OS dependent (will not work on Windows). Also it does not allow to use relative paths.
 – kgadek
 Oct 22, 2014 at 17:49
 Add a comment |
 0

 I tried:

 import os
 os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), os.pardir))
 
 Share
 Improve this answer
 Follow
 answered May 7, 2014 at 6:03
 gogasca gogasca
 8,944 5 5 gold badges 77 77 silver badges 120 120 bronze badges
 Add a comment |

 Your Answer

 Thanks for contributing an answer to Stack Overflow!

 * Please be sure to answer the question. Provide details and share your research!

 But avoid …

 * Asking for help, clarification, or responding to other answers.
 * Making statements based on opinion; back them up with references or personal experience.

 To learn more, see our tips on writing great answers.

 Sign up or log in

 Sign up using Google
 Sign up using Facebook
 Sign up using Email and Password
 Submit

 Post as a guest

 Name
 Email

 Required, but never shown

 Post as a guest

 Name
 Email

 Required, but never shown

 Post Your Answer Discard

 By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

 Not the answer you're looking for? Browse other questions tagged
 * python
 * path
 or ask your own question.

 * The Overflow Blog
 * ML and AI consulting-as-a-service (Ep. 541)
 * Why governments need open source more than ever
 * Featured on Meta
 * Ticket smash for [status-review] tag: Part Deux
 * We've added a "Necessary cookies only" option to the cookie consent popup
 * The [amazon] tag is being burninated
 * Microsoft Azure Collective launch and proposed tag changes
 * Temporary policy: ChatGPT is banned

 Linked

 542
 beyond top level package error in relative import
 5
 Python - Relative file locations when calling submodules
 0
 TypeError: 'str' object is not callable with path
 0
 How get path of specific parent directory in python
 1
 Django grabing before the BASE_DIR path

 Related

 6636
 How do I merge two dictionaries in a single expression in Python?
 6912
 How do I check whether a file exists without exceptions?
 5919
 How do I execute a program or call a system command?
 12516
 What does the "yield" keyword do in Python?
 5451
 How can I safely create a directory (possibly including intermediate directories)?
 3697
 How do I get the current time?
 5061
 Accessing the index in 'for' loops
 1573
 How do I get the filename without the extension from a path in Python?
 2677
 How do I get the last element of a list?

 Hot Network Questions

 * How to control the height and width of rectangular box in latex table?
 * Identify these old accounting machines
 * After SLS, what is the next rocket building project for NASA?
 * Is the vial necessary to Summon Greater Demon?
 * How did this ceiling exhaust fan get stuck on (and why did disconnecting this wire fix it)?
 * Being pushed out of a paper by a toxic postdoc - what should I do?
 * How can you achieve decent clock accuracy in microcontrollers (e.g., max 1 second drift in a year)? How do digital watch manufacturers accomplish it?
 * My supervisor is suggesting implementing an idea that they previously rejected
 * Connecting legacy Mac OS (10.3.9) to modern HTTPS via TLS
 * Potential and Field
 * In quantum field theory, why is vacuum considered to have the same properties as a particle?
 * Symsquare Number 04
 * Can a VGA monitor be connected to parallel port?
 * How did Leo Tolstoy approve Maude's English translation of War and Peace? Did he speak good English already?
 * "Candy Crush" a string
 * Arithmetic progression in LaTeX
 * Intel "Kernel processor" or "OS Kernel"
 * Will floating pantry shelves built with 2x2s be ok?
 * Can I combine Reckless Abandon with Debilitating Dichotomy?
 * Primes with Distinct Prime Digits
 * Repeating text watermark in background?
 * 1+2+3+4+… and −⅛
 * Where to put an inheritance of $1.4 million upon first receiving it
 * Why will changing the solvent crack the column for column chromatography?
 more hot questions
 Question feed

 Subscribe to RSS

 Question feed

 To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

 Stack Overflow

 * Questions
 * Help

 Products

 * Teams
 * Advertising
 * Collectives
 * Talent

 Company

 * About
 * Press
 * Work Here
 * Legal
 * Privacy Policy
 * Terms of Service
 * Contact Us
 * Cookie Settings
 * Cookie Policy

 Stack Exchange Network

 * Technology
 * Culture & recreation
 * Life & arts
 * Science
 * Professional
 * Business
 * API
 * Data
 * Blog
 * Facebook
 * Twitter
 * LinkedIn
 * Instagram

 Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA. rev 2023.2.24.43259

 Your privacy

 By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

 Accept all cookies Necessary cookies only
 Customize settings
this code is get the templates/blog1/page.html in b.py:
 path = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'blog1/page.html'))
 
but i want to get the parent dir location:
 aParent
 |--a
 | |---b.py
 | |---templates
 | |--------blog1
 | |-------page.html
 |--templates
 |--------blog1
 |-------page.html
 
and how to get the aParent location
thanks
 updated: 
this is right:
 dirname=os.path.dirname
path = os.path.join(dirname(dirname(__file__)), os.path.join('templates', 'blog1/page.html'))
 
or 
 path = os.path.abspath(os.path.join(os.path.dirname(__file__),".."))
 
 
 
 
 
 
 
 
    
 
 
  Tim  41.2k18 gold badges129 silver badges143 bronze badges
 
 
 
 
 asked May 12, 2010 at 8:57
 
 
    
 
 
 
 
 6
 
 
 
 
 
 
 
 You can apply dirname repeatedly to climb higher: dirname(dirname(file)). This can only go as far as the root package, however. If this is a problem, use os.path.abspath: dirname(dirname(abspath(file))).
 
 
 answered May 12, 2010 at 9:03
 
 
    
 
 
  Marcelo CantosMarcelo Cantos 179k38 gold badges324 silver badges363 bronze badges
 
 
 
 4
 
 
 
 
 
 
Use relative path with the  pathlib  module in Python 3.4+:
 from pathlib import Path
Path(__file__).parent
 
You can use multiple calls to parent to go further in the path:
 Path(__file__).parent.parent
 
As an alternative to specifying parent twice, you can use:
 Path(__file__).parents[1]
 
 
 
 
 answered Sep 21, 2016 at 13:18
 
 
    
 
 
 
 3
 
 
 
 
 
 
 os.path.abspath doesn't validate anything, so if we're already appending strings to __file__ there's no need to bother with dirname or joining or any of that. Just treat __file__ as a directory and start climbing:
 # climb to __file__'s parent's parent:
os.path.abspath(__file__ + "/../../")
 
That's far less convoluted than os.path.abspath(os.path.join(os.path.dirname(__file__),"..")) and about as manageable as dirname(dirname(__file__)). Climbing more than two levels starts to get ridiculous.
But, since we know how many levels to climb, we could clean this up with a simple little function:
 uppath = lambda _path, n: os.sep.join(_path.split(os.sep)[:-n])
# __file__ = "/aParent/templates/blog1/page.html"
&gt;&gt;&gt; uppath(__file__, 1)
'/aParent/templates/blog1'
&gt;&gt;&gt; uppath(__file__, 2)
'/aParent/templates'
&gt;&gt;&gt; uppath(__file__, 3)
'/aParent'
 
 
 
 
 answered Jan 4, 2013 at 3:38
 
 
    
 
 
  joemallerjoemaller 19.2k7 gold badges66 silver badges83 bronze badges
 
 
 
 2
 
 
 
 
 
 
 os.path.dirname(os.path.abspath(__file__))
 
Should give you the path to a.
But if b.py is the file that is currently executed, then you can achieve the same by just doing
 os.path.abspath(os.path.join('templates', 'blog1', 'page.html'))
 
 
 
 
 answered May 12, 2010 at 9:36
 
 
    
 
 
  Felix KlingFelix Kling 784k173 gold badges1083 silver badges1131 bronze badges
 
 
 
 2
 
 
 
 
 os.pardir is a better way for ../ and more readable. 
 import os
print os.path.abspath(os.path.join(given_path, os.pardir)) 
 
This will return the parent path of the given_path
 
 
 
 answered Nov 25, 2013 at 14:32
 
 
    
 
 
  Sun LiwenSun Liwen 1,2241 gold badge15 silver badges21 bronze badges
 
 
 
 
 
 
 
 
A simple way can be:
 import os
current_dir = os.path.abspath(os.path.dirname(__file__))
parent_dir = os.path.abspath(current_dir + "/../")
print parent_dir
 
 
 
 
 answered Aug 7, 2013 at 21:59
 
 
    
 
 
  Muneeb AliMuneeb Ali 2,0161 gold badge16 silver badges8 bronze badges
 
 
 
 0
 
 
 
 
 
 
May be join two .. folder, to get parent of the parent folder?
 path = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),"..",".."))
 
 
 
 
 answered May 12, 2010 at 9:26
 
 
    
 
 
  YOUYOU 118k34 gold badges186 silver badges218 bronze badges
 
 
 
 0
 
 
 
 
Here is another relatively simple solution that:
does not use dirname() (which does not work as expected on one level arguments like "file.txt" or relative parents like "..")
does not use abspath() (avoiding any assumptions about the current working directory) but instead preserves the relative character of paths
it just uses normpath and join:
 def parent(p):
 return os.path.normpath(os.path.join(p, os.path.pardir))
# Example:
for p in ['foo', 'foo/bar/baz', 'with/trailing/slash/', 
 'dir/file.txt', '../up/', '/abs/path']:
 print parent(p)
 
Result:
 .
foo/bar
with/trailing
dir
..
/abs
 
 
 
 
 answered Mar 19, 2014 at 16:03
 
 
    
 
 
  StefaanStefaan 4,6663 gold badges22 silver badges16 bronze badges
 
 
 
 
 
 
Use the following to jump to previous folder:
 os.chdir(os.pardir)
 
If you need multiple jumps a good and easy solution will be to use a simple decorator in this case.
 
 
 
 
 
 
    
 
 
  Zulu  8,4089 gold badges47 silver badges56 bronze badges
 
 
 
 
 answered Apr 3, 2015 at 21:22
 
 
    
 
 
  Marco smdmMarco smdm 1,0101 gold badge15 silver badges25 bronze badges
 
 
 
 
 
 
 
 
 
from os.path import basename, dirname
basename(dirname('foo/bar/foo_bar'))
 
 
 
 answered Apr 3, 2022 at 18:53
 
 
    
 
 
 
 1
 
 
 
 
 
 
I think use this is better:
 os.path.realpath(__file__).rsplit('/', X)[0]
In [1]: __file__ = "/aParent/templates/blog1/page.html"
In [2]: os.path.realpath(__file__).rsplit('/', 3)[0]
Out[3]: '/aParent'
In [4]: __file__ = "/aParent/templates/blog1/page.html"
In [5]: os.path.realpath(__file__).rsplit('/', 1)[0]
Out[6]: '/aParent/templates/blog1'
In [7]: os.path.realpath(__file__).rsplit('/', 2)[0]
Out[8]: '/aParent/templates'
In [9]: os.path.realpath(__file__).rsplit('/', 3)[0]
Out[10]: '/aParent'
 
 
 
 
 answered Feb 15, 2014 at 15:39
 
 
    
 
 
  dongweimingdongweiming 8131 gold badge8 silver badges7 bronze badges
 
 
 
 1
 
 
 
 
I tried: 
 import os
os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), os.pardir))
 
 
 
 
 answered May 7, 2014 at 6:03
 
 
    
 
 
  gogascagogasca 8,9445 gold badges77 silver badges120 bronze badges
How to get the parent dir location
https://stackoverflow.com/questions/2817264/how-to-get-the-parent-dir-location
https://www.geeksforgeeks.org/get-parent-of-current-directory-using-python/
Get parent of current directory using Python - GeeksforGeeks
2019-11-27
Nikhilaggarwal3
<div><div><p>In Python, <strong>OS module</strong> is used to interact with the operating system. It comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. The *os* and *os.path* modules include many functions to interact with the file system. <br />OS module provides various ways for getting the parent directory. Some of the ways are: </p><ul><li><a href="#abspath">Using os.path.abspath()</a> </li><li><a href="#dirname">Using os.path.dirname()</a> </li><li><a href="#relpath">Using os.path.relpath() and os.path.dirname()</a></li><li>Using Path().resolve().parent</li></ul><h2>Using os.path.abspath() to get parent of current directory</h2><p>os.path.abspath() can be used to get the parent directory. This method is used to get the normalized version of the path. This function also needs the help of <a href="http://geeksforgeeks.org/python-os-path-join-method/">os.path.join()</a> and os.pardir(). <br /><a href="http://geeksforgeeks.org/python-os-path-join-method/">os.path.join()</a> method in Python join one or more path components intelligently. This method concatenates various path components with exactly one directory separator (‘/’) following each non-empty part except the last path component. If the last path component to be joined is empty then a directory separator (‘/’) is put at the end. </p><blockquote><p><strong>Syntax:</strong> os.path.abspath(path)<br /><strong>Parameters:</strong> <br /><strong>path:</strong> A path-like object representing a file system path.<br /><strong>Return Type:</strong> Returns a string that is a normalized version of the path. </p></blockquote><p><strong>Example:</strong> </p><div><h2>Python3</h2><div><p><code>import</code> <code>os</code></p><p><code>path </code><code>=</code> <code>os.getcwd()</code></p><p><code>print</code><code>(</code><code>"Current Directory"</code><code>, path)</code></p><p><code>print</code><code>(os.path.abspath(os.path.join(path, os.pardir)))</code></p></div></div><p><strong>Output:</strong>  </p><div><p></p></div><h2>Using os.path.dirname() to get parent of current directory</h2><p><a href="https://www.geeksforgeeks.org/python-os-path-dirname-method/">os.path.dirname()</a> method in Python is used to get the directory name from the specified path. </p><blockquote><p><strong>Syntax: </strong>os.path.dirname(path)<br /><strong>Parameter:</strong> <br /><strong>path:</strong> A path-like object representing a file system path.<br /><strong>Return Type:</strong> This method returns a string value which represents the directory name from the specified path. </p></blockquote><p><strong>Example:</strong>  </p><div><h2>Python3</h2><div><p><code>import</code> <code>os</code></p><p><code>path </code><code>=</code> <code>os.getcwd()</code></p><p><code>print</code><code>(</code><code>"Current Directory"</code><code>, path)</code></p><p><code>print</code><code>()</code></p><p><code>parent </code><code>=</code> <code>os.path.dirname(path)</code></p><p><code>print</code><code>(</code><code>"Parent directory"</code><code>, parent)</code></p></div></div><p><strong>Output:</strong> </p><div><p></p></div><h2>Using os.path.relpath() and os.path.dirname()</h2><p>In the above examples, getting the parent directory was limited to one level, i.e. we were only able to get the parent of current directory upto one level only. Suppose we want to find the parent to the parent directory, then the above code fails. This can be achieved by using <a href="https://www.geeksforgeeks.org/python-os-path-relpath-method/">os.path.relpath()</a> and os.path.dirname() together. <br /><a href="https://www.geeksforgeeks.org/python-os-path-relpath-method/">os.path.relpath()</a> method in Python is used to get a relative filepath to the given path either from the current working directory or from the given directory.</p><blockquote><p><strong>Syntax: </strong>os.path.relpath(path, start = os.curdir)<br /><strong>Parameter:</strong> </p><ul><li><strong>path:</strong> A path-like object representing the file system path. </li><li><strong>start (optional):</strong> A path-like object representing the file system path. <br />The relative path for given path will be computed with respect to the directory indicated by start. The default value of this parameter is os.curdir which is a constant string used by the operating system to refer to the current directory.</li></ul><p><strong>Return Type: </strong>This method returns a string value which represents the relative file path to given path from the start directory.0222  </p></blockquote><p>To get the parent directory according to levels specified by the user, we will create a function getParent() which will take path and levels as arguments. Inside the function, a for loop will iterate level+1 numbers of time and os.path.dirname() will be called inside the for loop. Calling this function inside the for loop will give us the starting point from which os.path.relpath() will give the relative file path.</p><p><strong>Example:</strong></p><div><h2>Python3</h2><div><p><code>import</code> <code>os.path</code></p><p><code>def</code> <code>getParent(path, levels </code><code>=</code> <code>1</code><code>):</code></p><p><code>    </code><code>common </code><code>=</code> <code>path</code></p><p><code>    </code><code>for</code> <code>i </code><code>in</code> <code>range</code><code>(levels </code><code>+</code> <code>1</code><code>):</code></p><p><code>        </code><code>common </code><code>=</code> <code>os.path.dirname(common)</code></p><p><code>    </code><code>return</code> <code>os.path.relpath(path, common)</code></p><p><code>path </code><code>=</code> <code>'D:/Pycharm projects / GeeksforGeeks / Nikhil / gfg.txt'</code></p><p><code>print</code><code>(getParent(path, </code><code>2</code><code>))</code></p></div></div><p><strong>Output:</strong></p><div><p></p></div><h2>Using Path().resolve().parents to get parent of current directory</h2><blockquote><p><strong>Syntax:</strong> Path(path).resolve().parents[0]</p><p><strong>Parameter: </strong></p><ul><li><strong>path: </strong>path of the file or folder whose parent we want to fetch.</li></ul><p><strong>Return Type: </strong>It returns WindowsPath.parents object.</p></blockquote><p>Here we are using the path module to get the parent of current directory and instead of parents[0] we can also use parent.parent to fetch the parent of the current directory.</p><p><strong>Example:</strong></p><div><h2>Python3</h2><div><p><code>from</code> <code>pathlib </code><code>import</code> <code>Path</code></p><p><code>d </code><code>=</code> <code>Path(</code><code>"C:\\Users\\DELL\\Downloads"</code><code>).resolve().parents[</code><code>0</code><code>]</code></p><p><code>print</code><code>(d)</code></p></div></div><p><strong>Output:</strong></p><div><p></p></div><br /></div>||||I|||| Skip to content
 * Courses
 + For Working Professionals
 o DevOps(Live)
 o Data Structure & Algorithm Classes (Live)
 o System Design (Live)
 o Java Backend Developer (Live)
 o Full Stack Development with React & Node JS (Live)
 o Complete Data Science Program
 o Data Structure & Algorithm-Self Paced(C++/JAVA)
 o Data Structures & Algorithms in Python
 o Explore More Live Courses
 + For Students
 o Competitive Programming (Live)
 o Interview Preparation Course
 o Data Structure & Algorithm-Self Paced(C++/JAVA)
 o Data Structures & Algorithms in Python
 o Data Science (Live)
 o Full Stack Development with React & Node JS (Live)
 o GATE CS 2023 Test Series
 o OS DBMS CN for SDE Interview Preparation
 o Explore More Self-Paced Courses
 + Programming Languages
 o C++ Programming - Beginner to Advanced
 o Java Programming - Beginner to Advanced
 o C Programming - Beginner to Advanced
 o Python Foundation
 o JavaScript Foundation
 + Web Development
 o Full Stack Development with React & Node JS(Live)
 o Java Backend Development(Live)
 o React JS (Basic to Advanced)
 o JavaScript Foundation
 + Machine Learning and Data Science
 o Complete Data Science Program(Live)
 o Mastering Data Analytics
 + School Courses
 o CBSE Class 12 Computer Science
 o School Guide
 + All Courses
 * Tutorials
 + DSA
 + Data Structures
 o Arrays
 o Linked List
 o Stack
 o Queue
 o Binary Tree
 o Binary Search Tree
 o Heap
 o Hashing
 o Graph
 o Advanced Data Structure
 o Matrix
 o Strings
 o All Data Structures
 + Algorithms
 o Analysis of Algorithms
 - Asymptotic Analysis
 - Worst, Average and Best Cases
 - Asymptotic Notations
 - Little o and little omega notations
 - Lower and Upper Bound Theory
 - Analysis of Loops
 - Solving Recurrences
 - Amortized Analysis
 - What does 'Space Complexity' mean ?
 - Pseudo-polynomial Algorithms
 - Polynomial Time Approximation Scheme
 - A Time Complexity Question
 o Searching Algorithms
 o Sorting Algorithms
 o Graph Algorithms
 o Pattern Searching
 o Geometric Algorithms
 o Mathematical
 o Bitwise Algorithms
 o Randomized Algorithms
 o Greedy Algorithms
 o Dynamic Programming
 o Divide and Conquer
 o Backtracking
 o Branch and Bound
 o All Algorithms
 + Interview Corner
 o Company Preparation
 o Top Topics
 o Practice Company Questions
 o Interview Experiences
 o Experienced Interviews
 o Internship Interviews
 o Competitive Programming
 o Design Patterns
 o System Design Tutorial
 o Multiple Choice Quizzes
 + Languages
 o C
 o C++
 o Java
 o Python
 o JavaScript
 o PHP
 o C#
 o SQL
 o Scala
 o Perl
 o Go Language
 o Kotlin
 + Web Development
 o HTML
 o CSS
 o JavaScript
 o PHP
 o CSS Frameworks
 - Bootstrap
 - Tailwind CSS
 - Foundation CSS
 - Materialize CSS
 - Bulma
 - Pure CSS
 - Primer CSS
 - Blaze UI
 - Semantic UI
 o JavaScript Frameworks
 - AngularJS
 - Angular PrimeNG
 - Angular ngx Bootstrap
 - NodeJS
 - Express.js
 o JavaScript Libraries
 - jQuery
 - jQuery Mobile
 - jQuery UI
 - jQuery EasyUI
 - jQWidgets
 - ReactJS
 - React Bootstrap
 - React Rebass
 - React Desktop
 - React Suite
 - ReactJS Evergreen
 - ReactJS Reactstrap
 - Ant Design
 - BlueprintJS
 - p5.js
 - Lodash
 - TensorFlow.js
 - Moment.js
 - Collect.js
 o WordPress
 o JSON
 + School Learning
 o English Grammar
 o School Programming
 o Mathematics
 - Number System
 - Algebra
 - Trigonometry
 - Statistics
 - Probability
 - Geometry
 - Mensuration
 - Calculus
 o Maths Notes (Class 8-12)
 - Class 8 Notes
 - Class 9 Notes
 - Class 10 Notes
 - Class 11 Notes
 - Class 12 Notes
 o NCERT Solutions
 - Class 8 Maths Solution
 - Class 9 Maths Solution
 - Class 10 Maths Solution
 - Class 11 Maths Solution
 - Class 12 Maths Solution
 o RD Sharma Solutions
 - Class 8 Maths Solution
 - Class 9 Maths Solution
 - Class 10 Maths Solution
 - Class 11 Maths Solution
 - Class 12 Maths Solution
 o Physics Notes (Class 8-11)
 - Class 8 Notes
 - Class 9 Notes
 - Class 10 Notes
 - Class 11 Notes
 o Chemistry Notes
 - Class 8 Notes
 - Class 9 Notes
 - Class 10 Notes
 o Business Studies (Class 11th)
 o Business Studies (Class 12th)
 o Accountancy (Class 12th)
 o Statistics for Economics (Class 11th)
 + ML & Data Science
 o Machine Learning
 o Data Science
 + CS Subjects
 o Mathematics
 o Operating System
 o DBMS
 o Computer Networks
 o Computer Organization and Architecture
 o Theory of Computation
 o Compiler Design
 o Digital Logic
 o Software Engineering
 + GATE
 o GATE 2023 Test Series
 o GATE Computer Science Notes
 o Last Minute Notes
 o GATE CS Solved Papers
 o GATE CS Original Papers and Official Keys
 o GATE CS 2023 Syllabus
 o Important Topics for GATE CS
 o GATE 2023 Important Dates
 + Software Designs
 o Software Design Patterns
 o System Design Tutorial
 + GFG Sheets
 o Web Dev Cheat Sheets
 - HTML Cheat Sheet
 - CSS Cheat Sheet
 - Bootstrap Cheat Sheet
 - JS Cheat Sheet
 - jQuery Cheat Sheet
 - Angular Cheat Sheet
 o Company-Wise SDE Sheets
 - Facebook SDE Sheet
 - Amazon SDE Sheet
 - Apple SDE Sheet
 - Netflix SDE Sheet
 - Google SDE Sheet
 - Wipro Coding Sheet
 - Infosys Coding Sheet
 - TCS Coding Sheet
 - Cognizant Coding Sheet
 - HCL Coding Sheet
 o DSA Sheets
 - SDE Sheet
 - FAANG Coding Sheet
 - Love Babbar Sheet
 - Mass Recruiter Sheet
 - Product-Based Coding Sheet
 - Company-Wise Preparation Sheet
 - Array Sheet
 - String Sheet
 - Tree Sheet
 - Graph Sheet
 - DP Sheet
 + CS Exams/PSUs
 o ISRO
 - ISRO CS Original Papers and Official Keys
 - ISRO CS Solved Papers
 - ISRO CS Syllabus for Scientist/Engineer Exam
 o UGC NET
 - UGC NET CS Notes Paper II
 - UGC NET CS Notes Paper III
 - UGC NET CS Solved Papers
 + Student
 o Campus Ambassador Program
 o School Ambassador Program
 o Project
 o Geek of the Month
 o Campus Geek of the Month
 o Placement Course
 o Competitive Programming
 o Testimonials
 o Student Chapter
 o Geek on the Top
 o Internship
 o Careers
 + UPSC
 o Geography Notes
 o History Notes
 o Science & Tech. Notes
 o Ethics Notes
 o Polity Notes
 o Economics Notes
 o UPSC Previous Year Papers
 + SSC CGL
 o SSC CGL Syllabus
 o General Studies
 o English
 o Reasoning
 o Subjectwise Practice Papers
 o Previous Year Papers
 + Banking Exams
 o SBI Clerk
 - SBI Clerk Syllabus
 - General Awareness
 - English
 - Quantitative Aptitude
 - Reasoning Ability
 - SBI Clerk Practice Papers
 o SBI PO
 - SBI PO Syllabus
 - General Awareness
 - English
 - Quantitative Aptitude
 - Reasoning Ability
 - Previous Year Papers
 - SBI PO Practice Papers
 o IBPS PO
 - IBPS PO 2022 Syllabus
 - English Notes
 - Reasoning Notes
 - Previous Year Papers
 - Mock Question Papers
 o IBPS Clerk
 - IBPS Clerk Syllabus
 - English Notes
 - Previous Year Papers
 * Jobs
 + Apply for a Job
 + Apply through Jobathon
 + Post a Job
 + Hire through Jobathon
 * Practice
 + All DSA Problems
 + Problem of the Day
 + GFG SDE Sheet
 + Curated DSA Lists
 o Top 50 Array Problems
 o Top 50 String Problems
 o Top 50 Tree Problems
 o Top 50 Graph Problems
 o Top 50 DP Problems
 * Contests
 + GFG Weekly Coding Contest
 + Job-A-Thon: Hiring Challenge
 + BiWizard School Contest
 + All Contests and Events
 * 
 * 
 * 
 * Home
 * Saved Videos
 * Courses
 * 
 * GBlog
 * Puzzles
 * What's New ?
 Change Language
 * Data Structures and Algorithms
 * Interview Preparation
 * Data Science
 * Topic-wise Practice
 * C
 * C++
 * Java
 * Python
 * Latest Blogs
 * Competitive Programming
 * JavaScript
 * Machine Learning
 * Write & Earn
 * Web Development
 * Puzzles
 * Projects
 Related Articles
▲
 Open in App
 Not now

 Related Articles

 Write an Article
 * Write an Interview Experience
 * Get parent of current directory using Python
 * Python | os.path.join() method
 * OS Path module in Python
 * OS Module in Python with Examples
 * Create a directory in Python
 * Python: Check if a File or Directory Exists
 * Python | os.mkdir() method
 * Python | os.makedirs() method
 * Python | os.path.exists() method
 * Python | os.path.isfile() method
 * Python | os.path.isdir() method
 * Python | os.listdir() method
 * os.walk() in Python
 * How to use Glob() function to find files recursively in Python?
 * Python: Passing Dictionary as Arguments to Function
 * Python | Passing dictionary as keyword arguments
 * Python Exception Handling
 * Python Try Except
 * Errors and Exceptions in Python
 * Built-in Exceptions in Python
 * User-defined Exceptions in Python with Examples
 * NZEC error in Python
 * File Handling in Python
 * Open a File in Python
 * How to read from a file in Python
 Write an Article
 * Write an Interview Experience
 * Adding new column to existing DataFrame in Pandas
 * Python map() function
 * Read JSON file using Python
 * How to get column names in Pandas dataframe
 * Taking input in Python
 Write an Article
 * Write an Interview Experience
 * Get parent of current directory using Python
 * Python | os.path.join() method
 * OS Path module in Python
 * OS Module in Python with Examples
 * Create a directory in Python
 * Python: Check if a File or Directory Exists
 * Python | os.mkdir() method
 * Python | os.makedirs() method
 * Python | os.path.exists() method
 * Python | os.path.isfile() method
 * Python | os.path.isdir() method
 * Python | os.listdir() method
 * os.walk() in Python
 * How to use Glob() function to find files recursively in Python?
 * Python: Passing Dictionary as Arguments to Function
 * Python | Passing dictionary as keyword arguments
 * Python Exception Handling
 * Python Try Except
 * Errors and Exceptions in Python
 * Built-in Exceptions in Python
 * User-defined Exceptions in Python with Examples
 * NZEC error in Python
 * File Handling in Python
 * Open a File in Python
 * How to read from a file in Python
 Write an Article
 * Write an Interview Experience
 * Adding new column to existing DataFrame in Pandas
 * Python map() function
 * Read JSON file using Python
 * How to get column names in Pandas dataframe
 * Taking input in Python

 Get parent of current directory using Python

 Improve Article
 Save Article
 * Last Updated : 13 Oct, 2022
 * Read
 * Discuss
 Improve Article
 Save Article

 In Python, OS module is used to interact with the operating system. It comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. The *os* and *os.path* modules include many functions to interact with the file system.
 OS module provides various ways for getting the parent directory. Some of the ways are:

 * Using os.path.abspath()
 * Using os.path.dirname()
 * Using os.path.relpath() and os.path.dirname()
 * Using Path().resolve().parent

 Using os.path.abspath() to get parent of current directory

 os.path.abspath() can be used to get the parent directory. This method is used to get the normalized version of the path. This function also needs the help of os.path.join() and os.pardir().
 os.path.join() method in Python join one or more path components intelligently. This method concatenates various path components with exactly one directory separator (‘/’) following each non-empty part except the last path component. If the last path component to be joined is empty then a directory separator (‘/’) is put at the end.

 Syntax: os.path.abspath(path)
 Parameters:
 path: A path-like object representing a file system path.
 Return Type: Returns a string that is a normalized version of the path.

 Example:

 Python3




 # Python program to get parent 
 # directory 
 import os 
 # get current directory 
 path = os.getcwd() 
 print("Current Directory", path) 
 # prints parent directory 
 print(os.path.abspath(os.path.join(path, os.pardir)))
 

 Output:

 Using os.path.dirname() to get parent of current directory

 os.path.dirname() method in Python is used to get the directory name from the specified path.

 Syntax: os.path.dirname(path)
 Parameter:
 path: A path-like object representing a file system path.
 Return Type: This method returns a string value which represents the directory name from the specified path.

 Example:

 Python3




 # Python program to get parent 
 # directory 
 import os 
 # get current directory 
 path = os.getcwd() 
 print("Current Directory", path) 
 print() 
 # parent directory 
 parent = os.path.dirname(path) 
 print("Parent directory", parent)
 

 Output:

 Using os.path.relpath() and os.path.dirname()

 In the above examples, getting the parent directory was limited to one level, i.e. we were only able to get the parent of current directory upto one level only. Suppose we want to find the parent to the parent directory, then the above code fails. This can be achieved by using os.path.relpath() and os.path.dirname() together.
 os.path.relpath() method in Python is used to get a relative filepath to the given path either from the current working directory or from the given directory.

 Syntax: os.path.relpath(path, start = os.curdir)
 Parameter:

 * path: A path-like object representing the file system path.
 * start (optional): A path-like object representing the file system path.
 The relative path for given path will be computed with respect to the directory indicated by start. The default value of this parameter is os.curdir which is a constant string used by the operating system to refer to the current directory.

 Return Type: This method returns a string value which represents the relative file path to given path from the start directory.0222

 To get the parent directory according to levels specified by the user, we will create a function getParent() which will take path and levels as arguments. Inside the function, a for loop will iterate level+1 numbers of time and os.path.dirname() will be called inside the for loop. Calling this function inside the for loop will give us the starting point from which os.path.relpath() will give the relative file path.

 Example:

 Python3




 # Python program to get the 
 # parent directory 
 import os.path 
 # function to get parent 
 def getParent(path, levels = 1): 
 common = path 
 # Using for loop for getting 
 # starting point required for 
 # os.path.relpath() 
 for i in range(levels + 1): 
 # Starting point 
 common = os.path.dirname(common) 
 # Parent directory upto specified 
 # level 
 return os.path.relpath(path, common) 
 path = 'D:/Pycharm projects / GeeksforGeeks / Nikhil / gfg.txt'
 print(getParent(path, 2)) 
 

 Output:

 Using Path().resolve().parents to get parent of current directory

 Syntax: Path(path).resolve().parents[0]

 Parameter:

 * path: path of the file or folder whose parent we want to fetch.

 Return Type: It returns WindowsPath.parents object.

 Here we are using the path module to get the parent of current directory and instead of parents[0] we can also use parent.parent to fetch the parent of the current directory.

 Example:

 Python3




 from pathlib import Path 
 d = Path("C:\\Users\\DELL\\Downloads").resolve().parents[0]
 print(d) 
 

 Output:


 My Personal Notes arrow_drop_up
 Save

 Please Login to comment...

 Like

 Next
 Python | os.path.join() method
 Related Articles
 1. Get directory of current Python script
 2. How to Get directory of Current Script in Python?
 3. Python - Import from parent directory
 4. Change current working directory with Python
 5. Python - Get list of files in directory sorted by size
 6. Python - Get list of files in directory with size
 7. Get sorted file names from a directory by creation date in Python
 8. Get Location of Python site-packages Directory
 9. Get current date using Python
 10. Get current time in milliseconds using Python
 Article Contributed By :
 nikhilaggarwal3
 @nikhilaggarwal3
 Vote for difficulty


 Easy Normal Medium Hard Expert

 Improved By :
 * kunalmalvi18
 * anikakapoor
 * shlokdi35dq
 Article Tags :
 * Python file-handling-programs
 * Python os-module-programs
 * Python OS-path-module
 * python-file-handling
 * Python
 Practice Tags :
 * python
 Report Issue
 What's New
 Python Programming Foundation -Self Paced Course
 View Details
 Complete Interview Preparation Course
 View Details
 Master Data Science & ML
 View Details
 System Design- Live Classes
 View Details

 Improve your Coding Skills with Practice

 Try It!
 A-143, 9th Floor, Sovereign Corporate Tower,
 Sector-136, Noida, Uttar Pradesh - 201305
 feedback@geeksforgeeks.org
 * Company
 * About Us
 * Careers
 * In Media
 * Contact Us
 * Privacy Policy
 * Copyright Policy
 * Advertise with us
 * Learn
 * DSA
 * Algorithms
 * Data Structures
 * SDE Cheat Sheet
 * Machine learning
 * CS Subjects
 * Video Tutorials
 * Courses
 * News
 * Top News
 * Technology
 * Work & Career
 * Business
 * Finance
 * Lifestyle
 * Knowledge
 * Languages
 * Python
 * Java
 * CPP
 * Golang
 * C#
 * SQL
 * Kotlin
 * Web Development
 * Web Tutorials
 * Django Tutorial
 * HTML
 * JavaScript
 * Bootstrap
 * ReactJS
 * NodeJS
 * Contribute
 * Write an Article
 * Improve an Article
 * Pick Topics to Write
 * Write Interview Experience
 * Internships
 * Video Internship
 @geeksforgeeks , Some rights reserved
 We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy Got It !

 Start Your Coding Journey Now!

 Login Register
In Python, OS module is used to interact with the operating system. It comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. The *os* and *os.path* modules include many functions to interact with the file system. OS module provides various ways for getting the parent directory. Some of the ways are:    Using os.path.abspath()   Using os.path.dirname()   Using os.path.relpath() and os.path.dirname()  Using Path().resolve().parent  Using os.path.abspath() to get parent of current directory os.path.abspath() can be used to get the parent directory. This method is used to get the normalized version of the path. This function also needs the help of os.path.join() and os.pardir().  os.path.join() method in Python join one or more path components intelligently. This method concatenates various path components with exactly one directory separator (‘/’) following each non-empty part except the last path component. If the last path component to be joined is empty then a directory separator (‘/’) is put at the end.    Syntax: os.path.abspath(path) Parameters:  path: A path-like object representing a file system path. Return Type: Returns a string that is a normalized version of the path.    Example:   Python3   import os   path  = os.getcwd()   print ( "Current Directory" , path)   print (os.path.abspath(os.path.join(path, os.pardir)))     Output:       Using os.path.dirname() to get parent of current directory  os.path.dirname() method in Python is used to get the directory name from the specified path.    Syntax: os.path.dirname(path) Parameter:  path: A path-like object representing a file system path. Return Type: This method returns a string value which represents the directory name from the specified path.    Example:    Python3   import os   path  = os.getcwd()   print ( "Current Directory" , path)   print ()   parent  = os.path.dirname(path)   print ( "Parent directory" , parent)     Output:      Using os.path.relpath() and os.path.dirname() In the above examples, getting the parent directory was limited to one level, i.e. we were only able to get the parent of current directory upto one level only. Suppose we want to find the parent to the parent directory, then the above code fails. This can be achieved by using os.path.relpath() and os.path.dirname() together.  os.path.relpath() method in Python is used to get a relative filepath to the given path either from the current working directory or from the given directory.   Syntax: os.path.relpath(path, start = os.curdir) Parameter:    path: A path-like object representing the file system path.   start (optional): A path-like object representing the file system path. The relative path for given path will be computed with respect to the directory indicated by start. The default value of this parameter is os.curdir which is a constant string used by the operating system to refer to the current directory.   Return Type: This method returns a string value which represents the relative file path to given path from the start directory.0222    To get the parent directory according to levels specified by the user, we will create a function getParent() which will take path and levels as arguments. Inside the function, a for loop will iterate level+1 numbers of time and os.path.dirname() will be called inside the for loop. Calling this function inside the for loop will give us the starting point from which os.path.relpath() will give the relative file path.  Example:   Python3   import os.path   def getParent(path, levels  = 1 ):        common  = path        for i  in range (levels  + 1 ):            common  = os.path.dirname(common)        return os.path.relpath(path, common)   path  = 'D:/Pycharm projects / GeeksforGeeks / Nikhil / gfg.txt'   print (getParent(path,  2 ))     Output:      Using Path().resolve().parents to get parent of current directory   Syntax: Path(path).resolve().parents[0]  Parameter:     path: path of the file or folder whose parent we want to fetch.   Return Type: It returns WindowsPath.parents object.  Here we are using the path module to get the parent of current directory and instead of parents[0] we can also use parent.parent to fetch the parent of the current directory.  Example:   Python3   from pathlib  import Path   d  = Path( "C:\\Users\\DELL\\Downloads" ).resolve().parents[ 0 ]   print (d)     Output:
Get parent of current directory using Python - GeeksforGeeks
https://www.geeksforgeeks.org/get-parent-of-current-directory-using-python/
https://stackoverflow.com/questions/2491222/how-to-rename-a-file-using-python
How to rename a file using Python
2012-10-10
Zjm
<div><div>
<p>As of Python 3.4 one can use the <a href="https://docs.python.org/3/library/pathlib.html">pathlib</a> module to solve this.</p>
<p>If you happen to be on an older version, you can use the backported version found <a href="https://pypi.python.org/pypi/pathlib2/">here</a></p>
<p>Let's assume you are not in the root path (just to add a bit of difficulty to it) you want to rename, and have to provide a full path, we can look at this: </p>
<pre><code>some_path = 'a/b/c/the_file.extension'
</code></pre>
<p>So, you can take your path and create a <code>Path</code> object out of it:</p>
<pre><code>from pathlib import Path
p = Path(some_path)
</code></pre>
<p>Just to provide some information around this object we have now, we can extract things out of it. For example, if for whatever reason we want to rename the file by modifying the filename from <code>the_file</code> to <code>the_file_1</code>, then we can get the filename part:</p>
<pre><code>name_without_extension = p.stem
</code></pre>
<p>And still hold the extension in hand as well: </p>
<pre><code>ext = p.suffix
</code></pre>
<p>We can perform our modification with a simple string manipulation:</p>
<p>Python 3.6 and greater make use of f-strings!</p>
<pre><code>new_file_name = f"{name_without_extension}_1"
</code></pre>
<p>Otherwise:</p>
<pre><code>new_file_name = "{}_{}".format(name_without_extension, 1)
</code></pre>
<p>And now we can perform our rename by calling the <code>rename</code> method on the path object we created and appending the <code>ext</code> to complete the proper rename structure we want:</p>
<pre><code>p.rename(Path(p.parent, new_file_name + ext))
</code></pre>
<p>More shortly to showcase its simplicity: </p>
<p>Python 3.6+:</p>
<pre><code>from pathlib import Path
p = Path(some_path)
p.rename(Path(p.parent, f"{p.stem}_1_{p.suffix}"))
</code></pre>
<p>Versions less than Python 3.6 use the string format method instead:</p>
<pre><code>from pathlib import Path
p = Path(some_path)
p.rename(Path(p.parent, "{}_{}_{}".format(p.stem, 1, p.suffix))
</code></pre>
 </div>||||I|||| Stack Overflow
 1. About
 2. Products
 3. For Teams
 1. Stack Overflow Public questions & answers
 2. Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
 3. Talent Build your employer brand
 4. Advertising Reach developers & technologists worldwide
 5. About the company
 Loading…

 1. current community

 + Stack Overflow
 help chat
 + Meta Stack Overflow

 your communities

 Sign up or log in to customize your list.

 more stack exchange communities

 company blog
 2. 
 3. Log in
 4. Sign up
 1. Home
 2. 
 1. Public
 2. Questions
 3. Tags
 4. Users
 5. Companies
 6. Collectives
 7. Explore Collectives
 3. 
 1. Teams
 Stack Overflow for Teams – Start collaborating and sharing organizational knowledge. Create a free Team Why Teams?
 2. Teams
 3. Create free Team

 Collectives™ on Stack Overflow

 Find centralized, trusted content and collaborate around the technologies you use most.

 Learn more about Collectives

 Teams

 Q&A for work

 Connect and share knowledge within a single location that is structured and easy to search.

 Learn more about Teams

 How to rename a file using Python

 Ask Question
 Asked 12 years, 10 months ago
 Modified 6 months ago
 Viewed 679k times
 640

 I want to change a.txt to b.kml.

 * python
 * file-rename
 Share
 Improve this question
 Follow
 edited Oct 10, 2012 at 13:29
 user647772
 asked Mar 22, 2010 at 9:59
 zjm1126 zjm1126
 61.7k 77 77 gold badges 173 173 silver badges 219 219 bronze badges
 0
 Add a comment |

 17 Answers

 Sorted by: Reset to default
 Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first)
 1002

 Use os.rename:

 import os
 
 os.rename('a.txt', 'b.kml')
 

 Usage:

 os.rename('from.extension.whatever','to.another.extension')
 
 Share
 Improve this answer
 Follow
 edited Jun 29, 2022 at 12:29
 Teoretic
 2,385 1 1 gold badge 18 18 silver badges 28 28 bronze badges
 answered Mar 22, 2010 at 10:00
 YOU YOU
 118k 34 34 gold badges 186 186 silver badges 218 218 bronze badges
 8
 * 125
 Should be noted that if the files are not in the working directory you will need the full path.
 – EndermanAPM
 Mar 29, 2017 at 11:34
 * 1
 not really, on 3.7 ubuntu, works for me using relative paths
 – toing_toing
 Feb 28, 2019 at 15:51
 * 5
 @toing_toing of course it works, he probably just means that you should be aware of the current directory, and either specify the path relative to it, or just use the absolute path (like C:/folder/file.txt on Windows or /home/file.txt on Linux/MacOS).
 – Alex P.
 Jun 26, 2019 at 14:24
 * 3
 It's worth noting that this will silently overwrite files on Unix-like systems but fail with OSError on Windows systems. os.path.exists should be used to check if the target exists before renaming. This does create a "Time Of Check to Time Of Use" bug, but it's unlikely to cause issues. (I know of no easy way around this - see here .
 – AnnanFay
 Sep 28, 2019 at 16:59
 * 6
 If the user actually wants the file to be replaced on any operating system, one should use os.replace
 – LucG
 Apr 29, 2020 at 9:11
 | Show 3 more comments
 141

 File may be inside a directory, in that case specify the path:

 import os
 old_file = os.path.join("directory", "a.txt")
 new_file = os.path.join("directory", "b.kml")
 os.rename(old_file, new_file)
 
 Share
 Improve this answer
 Follow
 edited Jul 27, 2017 at 14:24
 davidism
 117k 25 25 gold badges 382 382 silver badges 332 332 bronze badges
 answered Oct 15, 2015 at 9:15
 Abdul Razak Abdul Razak
 2,574 2 2 gold badges 17 17 silver badges 24 24 bronze badges
 0
 Add a comment |
 87

 As of Python 3.4 one can use the pathlib module to solve this.

 If you happen to be on an older version, you can use the backported version found here

 Let's assume you are not in the root path (just to add a bit of difficulty to it) you want to rename, and have to provide a full path, we can look at this:

 some_path = 'a/b/c/the_file.extension'
 

 So, you can take your path and create a Path object out of it:

 from pathlib import Path
 p = Path(some_path)
 

 Just to provide some information around this object we have now, we can extract things out of it. For example, if for whatever reason we want to rename the file by modifying the filename from the_file to the_file_1, then we can get the filename part:

 name_without_extension = p.stem
 

 And still hold the extension in hand as well:

 ext = p.suffix
 

 We can perform our modification with a simple string manipulation:

 Python 3.6 and greater make use of f-strings!

 new_file_name = f"{name_without_extension}_1"
 

 Otherwise:

 new_file_name = "{}_{}".format(name_without_extension, 1)
 

 And now we can perform our rename by calling the rename method on the path object we created and appending the ext to complete the proper rename structure we want:

 p.rename(Path(p.parent, new_file_name + ext))
 

 More shortly to showcase its simplicity:

 Python 3.6+:

 from pathlib import Path
 p = Path(some_path)
 p.rename(Path(p.parent, f"{p.stem}_1_{p.suffix}"))
 

 Versions less than Python 3.6 use the string format method instead:

 from pathlib import Path
 p = Path(some_path)
 p.rename(Path(p.parent, "{}_{}_{}".format(p.stem, 1, p.suffix))
 
 Share
 Improve this answer
 Follow
 edited Sep 18, 2019 at 18:10
 answered Jul 27, 2017 at 14:21
 idjaw idjaw
 24.8k 7 7 gold badges 64 64 silver badges 80 80 bronze badges
 14
 * 7
 Why would you do this instead of the accepted answer? Seems far more complicated
 – rbennell
 Sep 7, 2017 at 13:14
 * 48
 Well @rbennell, most of this answer is an explanation. The answer is really just the three lines at the end. Furthermore, the accepted answer is made explicitly for that very name change. This answer provides a way to show how you can manipulate the filename to preserve parts that you want in the path or name of the file. Furthermore, the pathlib library is introduced in python 3.4 so sharing the answer here also provides exposure for a solid module to showcase its versatility and usage for more complicated requirements.
 – idjaw
 Sep 7, 2017 at 13:22
 * 9
 Thank you @idjaw, your comment is a good answer to a basic question of us beginners, a simple Why did you did that? . Also, it is refreshing to see non-hostile approach on internet to what is often considered as ignorant.
 – Igor V.
 Apr 26, 2018 at 5:33
 * 3
 @SasukeUchiha - The {} are for string formatting, which you can read about here . Ultimately, what is happening is that the {} get replaced with the variables that are passed in to the format method. So the first {} will hold what is in name_without_extension , and the second will hold the second argument which is simply 1 .
 – idjaw
 May 5, 2018 at 19:07
 * 4
 Using f-strings simplifies it even more. from pathlib import Path p = Path(some_path) version = 1 p.rename(Path(p.parent, f"{p.stem}_{version}" + p.suffix))
 – Liquidgenius
 May 4, 2019 at 16:17
 | Show 9 more comments
 70
 import shutil
 
 shutil.move('a.txt', 'b.kml')
 

 This will work to rename or move a file.

 Share
 Improve this answer
 Follow
 answered Mar 22, 2010 at 10:00
 Andy Balaam Andy Balaam
 6,263 6 6 gold badges 33 33 silver badges 36 36 bronze badges
 2
 * 44
 shutil.move is not a good option due to not being an atomic operation. If the file is open, for instance, shutil.move will create a file with new_name , but will not delete the file with old_name hence leaving you with two files. os.rename on the other hand will do nothing, which is a better option . With shutil.move , even if you caught the error, you would still have to worry about checking and deleting the rogue file. Just not worth it when a better tool exists: os.rename .
 – mvbentes
 Sep 20, 2017 at 17:37
 * @mvbentes it would be interesting to know the behaviour of pathlib respectively Path with renaming open - windows - files.
 – Timo
 Feb 16, 2022 at 13:32
 Add a comment |
 21

 os.rename(old, new)

 This is found in the Python docs: http://docs.python.org/library/os.html

 Share
 Improve this answer
 Follow
 edited Jul 27, 2017 at 14:25
 davidism
 117k 25 25 gold badges 382 382 silver badges 332 332 bronze badges
 answered Mar 22, 2010 at 10:00
 Joe Joe
 45.7k 32 32 gold badges 151 151 silver badges 242 242 bronze badges
 0
 Add a comment |
 14

 As of Python version 3.3 and later, it is generally preferred to use os.replace instead of os.rename so FileExistsError is not raised if the destination file already exists.

 assert os.path.isfile('old.txt')
 assert os.path.isfile('new.txt')
 
 os.rename('old.txt', 'new.txt')
 # Raises FileExistsError
 os.replace('old.txt', 'new.txt')
 # Does not raise exception
 
 assert not os.path.isfile('old.txt')
 assert os.path.isfile('new.txt')
 

 See the documentation.

 Share
 Improve this answer
 Follow
 edited Aug 10, 2021 at 20:37
 answered Aug 10, 2021 at 20:31
 Chris Collett Chris Collett
 726 8 8 silver badges 13 13 bronze badges
 Add a comment |
 13

 Use os.rename. But you have to pass full path of both files to the function. If I have a file a.txt on my desktop so I will do and also I have to give full of renamed file too.

 os.rename('C:\\Users\\Desktop\\a.txt', 'C:\\Users\\Desktop\\b.kml')
 
 Share
 Improve this answer
 Follow
 edited Oct 28, 2020 at 9:46
 Tiago Martins Peres
 13.5k 18 18 gold badges 85 85 silver badges 132 132 bronze badges
 answered Dec 8, 2017 at 5:33
 lonewolf lonewolf
 372 3 3 silver badges 10 10 bronze badges
 1
 * 6
 "Have to" isn't true. You can always substitute a relative file name for an absolute file name, and vice versa. What usually bites beginners is they don't understand how relative file names relate to the current working directory.
 – tripleee
 Oct 24, 2019 at 10:21
 Add a comment |
 4

 One important point to note here, we should check if any files exists with the new filename.

 suppose if b.kml file exists then renaming other file with the same filename leads to deletion of existing b.kml.

 import os
 
 if not os.path.exists('b.kml'):
 os.rename('a.txt','b.kml')
 
 Share
 Improve this answer
 Follow
 edited Mar 29, 2021 at 8:55
 Abdul Razak
 2,574 2 2 gold badges 17 17 silver badges 24 24 bronze badges
 answered Feb 13, 2021 at 14:55
 Lohith Lohith
 808 1 1 gold badge 9 9 silver badges 22 22 bronze badges
 1
 * 1
 This is vulnerable to race conditions. Prefer using either os.rename in a try / except or os.replace .
 – bfontaine
 Apr 14, 2022 at 7:56
 Add a comment |
 3
 import os
 
 # Set the path
 path = 'a\\b\\c' 
 # save current working directory
 saved_cwd = os.getcwd()
 # change your cwd to the directory which contains files
 os.chdir(path)
 os.rename('a.txt', 'b.klm')
 # moving back to the directory you were in 
 os.chdir(saved_cwd)
 
 Share
 Improve this answer
 Follow
 edited Jul 1, 2018 at 3:24
 Troy Hoffman
 181 1 1 silver badge 5 5 bronze badges
 answered Apr 2, 2018 at 1:17
 Tilak M Divakar Tilak M Divakar
 101 1 1 silver badge 5 5 bronze badges
 2
 * 2
 Be wary of doing it this way. You cannot always chdir() to a directory, e.g. what happens under Windows when it is a UNC? And doing a chdir() has side-effects. I would rather just specify the necessary paths to os.rename() directly, no chdir() ing.
 – JonBrave
 Nov 22, 2018 at 9:02
 * Changing global state (the current working directory) is not necessary to rename files.
 – Sören
 May 2, 2022 at 15:12
 Add a comment |
 3

 Using the Pathlib library's Path.rename instead of os.rename:

 import pathlib
 
 original_path = pathlib.Path('a.txt')
 new_path = original_path.rename('b.kml')
 
 Share
 Improve this answer
 Follow
 answered Nov 16, 2020 at 19:57
 kym kym
 623 5 5 silver badges 8 8 bronze badges
 4
 * Why is this better?
 – AnnoyinC
 Jun 7, 2021 at 13:03
 * 1
 It’s just easier to use this method if all your paths are already Pathlib objects.
 – kym
 Jun 9, 2021 at 2:27
 * You can already use os.rename with pathlib objects.
 – bfontaine
 Jun 30, 2022 at 15:43
 * You don't need to import os if you stick to pathlib methods.
 – LucG
 Jan 16 at 8:19
 Add a comment |
 1

 Here is an example using pathlib only without touching os which changes the names of all files in a directory, based on a string replace operation without using also string concatenation:

 from pathlib import Path
 
 path = Path('/talend/studio/plugins/org.talend.designer.components.bigdata_7.3.1.20200214_1052\components/tMongoDB44Connection')
 
 for p in path.glob("tMongoDBConnection*"):
 new_name = p.name.replace("tMongoDBConnection", "tMongoDB44Connection")
 new_name = p.parent/new_name
 p.rename(new_name)
 
 Share
 Improve this answer
 Follow
 edited Nov 22, 2021 at 13:34
 answered Nov 22, 2021 at 13:29
 gil.fernandes gil.fernandes
 12.3k 5 5 gold badges 58 58 silver badges 72 72 bronze badges
 Add a comment |
 0
 import shutil
 import os
 
 files = os.listdir("./pics/") 
 
 for key in range(0, len(files)):
 print files[key]
 shutil.move("./pics/" + files[key],"./pics/img" + str(key) + ".jpeg")
 

 This should do it. python 3+

 Share
 Improve this answer
 Follow
 edited Apr 18, 2020 at 20:17
 petezurich
 8,730 9 9 gold badges 40 40 silver badges 56 56 bronze badges
 answered Sep 30, 2017 at 12:40
 Naveen Naveen
 295 1 1 gold badge 3 3 silver badges 12 12 bronze badges
 2
 * ... or use enumerate for a slightly more readable version : for key, fname in enumerate(files): …
 – Nicolas D
 Oct 10, 2018 at 9:09
 * How can you write print files[key] and "python 3+" in the same answer?
 – bfontaine
 Jun 30, 2022 at 15:45
 Add a comment |
 0

 How to change the first letter of filename in a directory:

 import os
 path = "/"
 
 for file in os.listdir(path):
 os.rename(path + file, path + file.lower().capitalize())
 
 then = os.listdir(path)
 print(then)
 
 Share
 Improve this answer
 Follow
 answered Jul 22, 2022 at 21:10
 Elvin Aghammadzada Elvin Aghammadzada
 683 6 6 silver badges 20 20 bronze badges
 Add a comment |
 -1

 If you are Using Windows and you want to rename your 1000s of files in a folder then: You can use the below code. (Python3)

 import os
 
 path = os.chdir(input("Enter the path of the Your Image Folder : ")) #Here put the path of your folder where your images are stored
 
 image_name = input("Enter your Image name : ") #Here, enter the name you want your images to have
 
 i = 0
 
 for file in os.listdir(path):
 
 new_file_name = image_name+"_" + str(i) + ".jpg" #here you can change the extention of your renmamed file.
 os.rename(file,new_file_name)
 
 i = i + 1
 
 input("Renamed all Images!!")
 
 Share
 Improve this answer
 Follow
 answered Sep 19, 2020 at 9:22
 Khan Saad Khan Saad
 789 1 1 gold badge 7 7 silver badges 25 25 bronze badges
 Add a comment |
 -2

 os.chdir(r"D:\Folder1\Folder2")
 os.rename(src,dst)
 #src and dst should be inside Folder2

 Share
 Improve this answer
 Follow
 answered Dec 11, 2020 at 18:46
 sauravjoshi23 sauravjoshi23
 787 7 7 silver badges 9 9 bronze badges
 Add a comment |
 -4
 import os
 import re
 from pathlib import Path
 
 for f in os.listdir(training_data_dir2):
 for file in os.listdir( training_data_dir2 + '/' + f):
 oldfile= Path(training_data_dir2 + '/' + f + '/' + file)
 newfile = Path(training_data_dir2 + '/' + f + '/' + file[49:])
 p=oldfile
 p.rename(newfile)
 
 Share
 Improve this answer
 Follow
 edited Apr 18, 2020 at 20:17
 petezurich
 8,730 9 9 gold badges 40 40 silver badges 56 56 bronze badges
 answered May 31, 2018 at 13:22
 issam issam
 93 3 3 bronze badges
 1
 * 4
 Hard-coding forward slash as the path separator and mixing old-style os.path with modern pathlib is quite iffy. Go all the way with pathlib instead.
 – tripleee
 Oct 24, 2019 at 10:23
 Add a comment |
 -6

 You can use os.system to invoke terminal to accomplish the task:

 os.system('mv oldfile newfile')
 
 Share
 Improve this answer
 Follow
 answered Jan 11, 2016 at 5:02
 user5449023 user5449023
 2
 * yes, this will work only on a unix-based machine as mv is a unix builtin commandline program to move/rename a file.
 – Mikhail Geyer
 Nov 20, 2016 at 18:42
 * 18
 Why would you invoke a terminal and define a UNIX only command when you can do it from python in a multi-platform way?
 – EndermanAPM
 Mar 29, 2017 at 11:34
 Add a comment |
 Highly active question. Earn 10 reputation (not counting the association bonus) in order to answer this question. The reputation requirement helps protect this question from spam and non-answer activity.

 Not the answer you're looking for? Browse other questions tagged
 * python
 * file-rename
 or ask your own question.

 * Stack Overflow Blog
 * Why developer experience is the key to better software, straight from the...
 * The frontier of computing: Q&A with IBM quantum computing research
 * Featured on Meta
 * Accessibility Update: Colors
 * Should we burninate the [balance] tag?
 * Collectives: The next iteration
 * Temporary policy: ChatGPT is banned

 Linked

 0
 How to rename part of a filename represented as string in Python 3
 -2
 How to erase the first character from all files (on Windows) into a folder using Python 3?
 0
 incrementing image number python
 -1
 Rename part of the name in any files or directories in Python
 0
 how can i change only the first letter of a filename into uppercase?
 -2
 python program to rename the file with current date in MMDDYYY format and send email with attachment
 -1
 How to copy a file with a timestam
 -1
 converting .out file into .txt file using cmd/powershell/python
 0
 How can i rename names of the files in a folder?
 414
 Rename multiple files in a directory in Python
 See more linked questions

 Related

 6620
 How do I merge two dictionaries in a single expression?
 6893
 How do I check whether a file exists without exceptions?
 7115
 What are metaclasses in Python?
 7636
 Does Python have a ternary conditional operator?
 2592
 How do I get a substring of a string in Python?
 5023
 How do I make a flat list out of a list of lists?
 3244
 How do I concatenate two lists in Python?
 4088
 Iterating over dictionaries using 'for' loops
 3588
 Does Python have a string 'contains' substring method?
 3154
 How can I delete a file or folder in Python?

 Hot Network Questions

 * Sum of Consecutive Squares
 * Searching text about school girl growing wings and trying to hide them at first
 * Why do Russians refer to the war in Ukraine as "всем известные событие"?
 * A Murder Mystery
 * Can one connect two technic pins end-to-end?
 * Are there other countries besides Türkiye that insist their name be written in English using diacritics (or even other letters) not common in English?
 * Why is Gravity’s Rainbow considered postmodern, yet Finnegans Wake is not?
 * std::move and lifetime of temporary objects
 * How to halve DC motor speed without using PWM
 * What did Paul McCartney mean by "Oh, yesterday came suddenly"?
 * The stock brakes on many e-bikes may be inadequate. What changes would make them adequate, and at what cost?
 * What is this symbol?
 * Exactly two neighbors
 * How to run `usepackage{times}` while keeping texttt font the same
 * Will any Oxford College accommodate a family including children?
 * What does "invalidate" mean in this context?
 * Is this Stanford certificate real?
 * DisplayPort downstream limited to 1920×1080
 * Why did so few militaries use semi automatic rifles as their standard issue infantry weapon?
 * Can an aircraft use ram air to generate power while flying?
 * Can someone choose to not use their “get out of jail free”-card in Monopoly?
 * How does Freedom of Movement interact with magical effects which increase movement costs?
 * Is it legal for a company to deduct their FICA match from a W2 employee's pay?
 * How to decide the sequence of cheeses for a cheese tasting event?
 more hot questions
 Question feed

 Subscribe to RSS

 Question feed

 To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

 Stack Overflow

 * Questions
 * Help

 Products

 * Teams
 * Advertising
 * Collectives
 * Talent

 Company

 * About
 * Press
 * Work Here
 * Legal
 * Privacy Policy
 * Terms of Service
 * Contact Us
 * Cookie Settings
 * Cookie Policy

 Stack Exchange Network

 * Technology
 * Culture & recreation
 * Life & arts
 * Science
 * Professional
 * Business
 * API
 * Data
 * Blog
 * Facebook
 * Twitter
 * LinkedIn
 * Instagram

 Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA. rev 2023.2.7.43225

 Your privacy

 By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

 Accept all cookies Customize settings
As of Python 3.4 one can use the pathlib module to solve this.
If you happen to be on an older version, you can use the backported version found here 
Let's assume you are not in the root path (just to add a bit of difficulty to it) you want to rename, and have to provide a full path, we can look at this: 
 some_path = 'a/b/c/the_file.extension'
 
So, you can take your path and create a Path object out of it:
 from pathlib import Path
p = Path(some_path)
 
Just to provide some information around this object we have now, we can extract things out of it. For example, if for whatever reason we want to rename the file by modifying the filename from the_file to the_file_1, then we can get the filename part:
 name_without_extension = p.stem
 
And still hold the extension in hand as well: 
 ext = p.suffix
 
We can perform our modification with a simple string manipulation:
Python 3.6 and greater make use of f-strings!
 new_file_name = f"{name_without_extension}_1"
 
Otherwise:
 new_file_name = "{}_{}".format(name_without_extension, 1)
 
And now we can perform our rename by calling the rename method on the path object we created and appending the ext to complete the proper rename structure we want:
 p.rename(Path(p.parent, new_file_name + ext))
 
More shortly to showcase its simplicity: 
Python 3.6+:
 from pathlib import Path
p = Path(some_path)
p.rename(Path(p.parent, f"{p.stem}_1_{p.suffix}"))
 
Versions less than Python 3.6 use the string format method instead:
 from pathlib import Path
p = Path(some_path)
p.rename(Path(p.parent, "{}_{}_{}".format(p.stem, 1, p.suffix))
How to rename a file using Python
https://stackoverflow.com/questions/2491222/how-to-rename-a-file-using-python
https://www.tutorialspoint.com/python/os_rename.htm
Python os.rename() Method
2021-07-28
None
<div><div>
<hr />
<h2>Description</h2>
<p>Python method <b>rename()</b> renames the file or directory <i>src</i> to <i>dst</i>.If <i>dst</i> is a file or directory(already present), <a href="/python/standard_exceptions.htm">OSError</a> will be raised.</p>
<h2>Syntax</h2>
<p>Following is the syntax for <b>rename()</b> method −</p>
<pre>os.rename(src, dst)
</pre>
<h2>Parameters</h2>
<ul>
<li><p><b>src</b> − This is the actual name of the file or directory.</p></li>
<li><p><b>dst</b> − This is the new name of the file or directory.</p></li>
</ul>
<h2>Return Value</h2>
<p>This method does not return any value.</p>
<h2>Example</h2>
<p>The following example shows the usage of rename() method.</p>
<pre># !/usr/bin/python
import os, sys
# listing directories
print "The dir is: %s"%os.listdir(os.getcwd())
# renaming directory ''tutorialsdir"
os.rename("tutorialsdir","tutorialsdirectory")
print "Successfully renamed."
# listing directories after renaming "tutorialsdir"
print "the dir is: %s" %os.listdir(os.getcwd())\
</pre>
<p>When we run above program, it produces following result −</p>
<pre>The dir is:
 [ 'a1.txt','resume.doc','a3.py','tutorialsdir','amrood.admin' ]
Successfully renamed.
The dir is:
 [ 'a1.txt','resume.doc','a3.py','tutorialsdirectory','amrood.admin' ]
</pre>
<p>python_files_io.htm</p>
	</div>||||I|||| * Home
 * Coding Ground
 * Jobs
 * Whiteboard
 * Tools
 * Corporate Training
 Teach with us
 * 
 * 
 * 
 * 
 * 
 * Login
 * Category
 + Academic Tutorials
 + Big Data & Analytics
 + Computer Programming
 + Computer Science
 + Databases
 + DevOps
 + Digital Marketing
 + Engineering Tutorials
 + Exams Syllabus
 + Famous Monuments
 + GATE Exams
 + Latest Technologies
 + Machine Learning
 + Mainframe Development
 + Management Tutorials
 + Mathematics Tutorials
 + Microsoft Technologies
 + Misc tutorials
 + Mobile Development
 + Java Technologies
 + Python Technologies
 + SAP Tutorials
 + Programming Scripts
 + Selected Reading
 + Software Quality
 + Soft Skills
 + Telecom Tutorials
 + UPSC IAS Exams
 + Web Development
 + Sports Tutorials
 + XML Technologies
 + Multi-Language
 + Interview Questions
 * Prime Packs
 * Courses
 * eBooks
 * Library
 * Articles
 Login
 * Python Basic Tutorial
 * Python - Home
 * Python - Overview
 * Python - Environment Setup
 * Python - Basic Syntax
 * Python - Comments
 * Python - Variables
 * Python - Data Types
 * Python - Operators
 * Python - Decision Making
 * Python - Loops
 * Python - Numbers
 * Python - Strings
 * Python - Lists
 * Python - Tuples
 * Python - Dictionary
 * Python - Date & Time
 * Python - Functions
 * Python - Modules
 * Python - Files I/O
 * Python - Exceptions
 * Python Advanced Tutorial
 * Python - Classes/Objects
 * Python - Reg Expressions
 * Python - CGI Programming
 * Python - Database Access
 * Python - Networking
 * Python - Sending Email
 * Python - Multithreading
 * Python - XML Processing
 * Python - GUI Programming
 * Python - Further Extensions
 * Python Useful Resources
 * Python - Questions and Answers
 * Python - Quick Guide
 * Python - Tools/Utilities
 * Python - Useful Resources
 * Python - Discussion
 * Selected Reading
 * UPSC IAS Exams Notes
 * Developer's Best Practices
 * Questions and Answers
 * Effective Resume Writing
 * HR Interview Questions
 * Computer Glossary
 * Who is Who

 Python os.rename() Method

 Previous Page
 Next Page

 Description

 Python method rename() renames the file or directory src to dst.If dst is a file or directory(already present), OSError will be raised.

 Syntax

 Following is the syntax for rename() method −

 
 os.rename(src, dst)
 

 Parameters

 * src − This is the actual name of the file or directory.

 * dst − This is the new name of the file or directory.

 Return Value

 This method does not return any value.

 Example

 The following example shows the usage of rename() method.

 
 # !/usr/bin/python
 
 import os, sys
 
 # listing directories
 print "The dir is: %s"%os.listdir(os.getcwd())
 
 # renaming directory ''tutorialsdir"
 os.rename("tutorialsdir","tutorialsdirectory")
 
 print "Successfully renamed."
 
 # listing directories after renaming "tutorialsdir"
 print "the dir is: %s" %os.listdir(os.getcwd())\
 

 When we run above program, it produces following result −

 
 The dir is:
 [ 'a1.txt','resume.doc','a3.py','tutorialsdir','amrood.admin' ]
 Successfully renamed.
 The dir is:
 [ 'a1.txt','resume.doc','a3.py','tutorialsdirectory','amrood.admin' ]
 
 python_files_io.htm
 Previous Page Print Page Next Page
 Advertisements


 Annual Membership

 Enjoy unlimited access on 5500+ Hand Picked Quality Video Courses

 Subscribe Now

 Training for a Team

 Affordable solution to train a team and make them project ready.

 Submit Demo Request
 * About us
 * Refund Policy
 * Terms of use
 * Privacy Policy
 * FAQ's
 * Contact

 © Copyright 2023. All Rights Reserved.

 We make use of First and third party cookies to improve our user experience. By using this website, you agree with our Cookies Policy. Agree Learn more

Description
Python method rename() renames the file or directory src to dst.If dst is a file or directory(already present), OSError will be raised.
Syntax
Following is the syntax for rename() method −
os.rename(src, dst)
Parameters
  src − This is the actual name of the file or directory. 
  dst − This is the new name of the file or directory. 
Return Value
This method does not return any value.
Example
The following example shows the usage of rename() method.
# !/usr/bin/python
import os, sys
# listing directories
print "The dir is: %s"%os.listdir(os.getcwd())
# renaming directory ''tutorialsdir"
os.rename("tutorialsdir","tutorialsdirectory")
print "Successfully renamed."
# listing directories after renaming "tutorialsdir"
print "the dir is: %s" %os.listdir(os.getcwd())\
When we run above program, it produces following result −
The dir is:
 [ 'a1.txt','resume.doc','a3.py','tutorialsdir','amrood.admin' ]
Successfully renamed.
The dir is:
 [ 'a1.txt','resume.doc','a3.py','tutorialsdirectory','amrood.admin' ]
python_files_io.htm
Python os.rename() Method
https://www.tutorialspoint.com/python/os_rename.htm
https://www.askpython.com/python/examples/rename-a-file-directory-python
How to Rename a File/Directory in Python? - AskPython
2020-06-24
Rnzo; Safa Mulani
<div><div><main><article><div><p>Hello, I hope you are doing well! In this article, we will <strong>rename a file or directory in Python</strong>.</p><hr/><h2>Rename a File/Directory in Python using the os module</h2><p><a href="https://www.askpython.com/python-modules/python-os-module-10-must-know-functions">Python os module</a> offers various functions to deal and interact with the underlying operating system of the particular device.</p><p>Python <code>os.rename() function</code> enable us to rename a file or directory, directly from command prompt or IDE. The os.rename() function alters the name of the source/input/current directory or file to a specified/user-defined name.</p><p>Thus, through Python os module, all the system level interactions can be performed.</p><p>Now, let us have a look at the syntax of Python os.rename() function.</p><hr/><h3>Syntax of Python os.rename() function</h3><p>Have a look at the below syntax:</p><div><pre>import os
os.rename(source,destination)
</pre></div><p>In order to use the rename() function, we need to import Python os module.</p><p>Further, the following parameters needs to be provided to the rename() function:</p><ul><li><code>source</code>: The current name of the file or directory.</li><li><code>destination</code>: The name which would replace the current name of file/directory.</li></ul><p>The os.rename() function <strong>does not return</strong> any value. It only renames the specified file/directory.</p><p>Having understood the working and syntax of rename() function, let us now implement the same through examples in the below section.</p><hr/><h3>Implementing Python os.rename() function through examples</h3><p>Let’s try to <strong>rename a directory</strong> using the os.rename function</p><p><strong>Example:</strong></p><div><pre>import os
os.chdir(r"C:/Users/HP/OneDrive/Desktop/")
os.rename("Programming","PRACTICE")
print("The Directory has been successfully renamed!")
</pre></div><p>The <code>os.chdir() function</code> is used to change the current working directory.</p><p><strong>Output:</strong></p><div><pre>The Directory has been successfully renamed!
</pre></div><p><strong>Directory after updating the name</strong>:</p><div><figure><figcaption><strong>Directory Renamed As PRACTICE</strong></figcaption></figure></div><p>Here, we have renamed the Directory ‘Programming’ to ‘PRACTICE’ using rename() function.</p><p>Now, let us try to <strong>rename a file</strong> using Python os.rename() function.</p><p><strong>Example:</strong></p><div><pre>import os
os.rename("C:/Users/HP/OneDrive/Desktop/New.txt","C:/Users/HP/OneDrive/Desktop/ss.txt")
print("The File has been successfully renamed!")
</pre></div><p><strong>Output:</strong></p><div><pre>The File has been successfully renamed!
</pre></div><p><strong>File after updating the name —</strong></p><div><figure><figcaption><strong>Python Rename File</strong></figcaption></figure></div><p>Here, we have updated/renamed a file to <strong>ss.txt</strong> using rename() function.</p><hr/><h2>Conclusion</h2><p>By this, we have come to the end of this topic. Please feel free to comment below, in case you come across any doubt.</p><p>For more such articles related to Python, do visit <a href="https://www.askpython.com/">Python@AskPython</a>.</p><hr/><h2>References</h2><ul><li>Python Rename Directory — JournalDev</li></ul></div></article></main></div></div>||||I|||| Skip to content
 Main Menu
 * Home
 * Python Course
 * Start Here

 How to Rename a File/Directory in Python?

 By Safa Mulani / June 24, 2020

 Hello, I hope you are doing well! In this article, we will rename a file or directory in Python.

 Rename a File/Directory in Python using the os module

 Python os module offers various functions to deal and interact with the underlying operating system of the particular device.

 Python os.rename() function enable us to rename a file or directory, directly from command prompt or IDE. The os.rename() function alters the name of the source/input/current directory or file to a specified/user-defined name.

 Thus, through Python os module, all the system level interactions can be performed.

 Now, let us have a look at the syntax of Python os.rename() function.

 Syntax of Python os.rename() function

 Have a look at the below syntax:

 
 import os
 os.rename(source,destination)
 

 In order to use the rename() function, we need to import Python os module.

 Further, the following parameters needs to be provided to the rename() function:

 * source: The current name of the file or directory.
 * destination: The name which would replace the current name of file/directory.

 The os.rename() function does not return any value. It only renames the specified file/directory.

 Having understood the working and syntax of rename() function, let us now implement the same through examples in the below section.

 Implementing Python os.rename() function through examples

 Let’s try to rename a directory using the os.rename function

 Example:

 
 import os
 os.chdir(r"C:/Users/HP/OneDrive/Desktop/")
 
 os.rename("Programming","PRACTICE")
 
 print("The Directory has been successfully renamed!")
 
 

 The os.chdir() function is used to change the current working directory.

 Output:

 
 The Directory has been successfully renamed!
 

 Directory after updating the name:

 Directory Renamed As PRACTICE

 Here, we have renamed the Directory ‘Programming’ to ‘PRACTICE’ using rename() function.

 Now, let us try to rename a file using Python os.rename() function.

 Example:

 
 import os
 
 os.rename("C:/Users/HP/OneDrive/Desktop/New.txt","C:/Users/HP/OneDrive/Desktop/ss.txt")
 
 print("The File has been successfully renamed!")
 

 Output:

 
 The File has been successfully renamed!
 

 File after updating the name —

 Python Rename File

 Here, we have updated/renamed a file to ss.txt using rename() function.

 Conclusion

 By this, we have come to the end of this topic. Please feel free to comment below, in case you come across any doubt.

 For more such articles related to Python, do visit Python@AskPython.

 References

 * Python Rename Directory — JournalDev
 Post navigation
 ← Previous Post
 Next Post →
 Search for:

 Recent Posts

 * Network Flow Optimization in Python: A Comprehensive Guide
 * Survival Analysis in Python: A Comprehensive Guide with Examples
 * Bayesian Inference in Python: A Comprehensive Guide with Examples
 * How to Skip a Point in Python if Statement: 3 Easy Methods
 * Finding Maximum Disk Space: Time and Space Complexity Analysis
 * How to Make API Calls in Python with Bearer Token Authentication
 * Laplace Distribution in Python [with Examples]
 * Floyd-Warshall Algorithm in Python: Shortest Path Between Cities
 * How to Debug and Fix Segmentation Faults in Python
 * Stochastic Indicator: Python Implementation

 Favorite Sites

 * GoLang Tutorials
 * VM-Help
 * Linux Tutorials
 * MySQL Tutorials
 * CodeForGeek
 * Mkyong
 Copyright © 2024 AskPython · All Rights Reserved
 Privacy Policy · Terms and Conditions · Contact · About · Team
 AskPython is part of Diyansh IT Services Private Limited
Hello, I hope you are doing well! In this article, we will rename a file or directory in Python.  Rename a File/Directory in Python using the os module  Python os module offers various functions to deal and interact with the underlying operating system of the particular device. Python os.rename() function enable us to rename a file or directory, directly from command prompt or IDE. The os.rename() function alters the name of the source/input/current directory or file to a specified/user-defined name. Thus, through Python os module, all the system level interactions can be performed. Now, let us have a look at the syntax of Python os.rename() function.  Syntax of Python os.rename() function Have a look at the below syntax:  import os
os.rename(source,destination)
  In order to use the rename() function, we need to import Python os module. Further, the following parameters needs to be provided to the rename() function:   source: The current name of the file or directory.  destination: The name which would replace the current name of file/directory.  The os.rename() function does not return any value. It only renames the specified file/directory. Having understood the working and syntax of rename() function, let us now implement the same through examples in the below section.  Implementing Python os.rename() function through examples Let’s try to rename a directory using the os.rename function  Example:   import os
os.chdir(r"C:/Users/HP/OneDrive/Desktop/")
os.rename("Programming","PRACTICE")
print("The Directory has been successfully renamed!")
  The os.chdir() function is used to change the current working directory.  Output:   The Directory has been successfully renamed!
   Directory after updating the name:    Directory Renamed As PRACTICE    Here, we have renamed the Directory ‘Programming’ to ‘PRACTICE’ using rename() function. Now, let us try to rename a file using Python os.rename() function.  Example:   import os
os.rename("C:/Users/HP/OneDrive/Desktop/New.txt","C:/Users/HP/OneDrive/Desktop/ss.txt")
print("The File has been successfully renamed!")
   Output:   The File has been successfully renamed!
   File after updating the name —     Python Rename File    Here, we have updated/renamed a file to ss.txt using rename() function.  Conclusion By this, we have come to the end of this topic. Please feel free to comment below, in case you come across any doubt. For more such articles related to Python, do visit Python@AskPython.  References  Python Rename Directory — JournalDev
How to Rename a File/Directory in Python? - AskPython
https://www.askpython.com/python/examples/rename-a-file-directory-python