how to change file name and extension in pyhon?
<p>I want to move and rename file called <code>malicious.txt</code> located at path <code>/home/dina/A</code> to a new location <code>/home/dina/b</code> with a new name based on <code>apkName</code> (e.g. <code>a.apk</code> or <code>b.apk</code>, etc) I want the final name to have <code>.json</code> extension instead of <code>.apk</code> extension - e.g <code>a.json</code> and <code>b.json</code></p>

<p>I tried :</p>

<pre><code>import os
os.rename("malicious.txt",apkName)
</code></pre>

<p>But it removes <code>malicious.txt</code> without appear any other files.</p>

<p>The following should rename "malicious.txt" to be name of apkfile with extension of ".json"</p>

<pre><code>import os
apkName = "a.apk"
apkFullpath = os.path.join(os.path.sep,"home","dina","a",apkName)
jsonName = os.path.splitext(apkName)[0]+".json"
jsonFullpath = os.path.join(os.path.sep,"home","dina","b",jsonName)
os.rename("malicious.txt",jsonName)
</code></pre>

<p>Note that you can rename file name only once (after the first time of rename, you won't be able to access the old name)</p>

<p>for more info about <strong>os.path.join</strong> and <strong>os.path.sep</strong></p>

<p><a href="https://docs.python.org/2/library/os.path.html" rel="nofollow">https://docs.python.org/2/library/os.path.html</a></p>

<p><strong>os.path.join(path, *paths)</strong></p>

<p>Join one or more path components intelligently. The return value is the concatenation of path and any members of *paths with exactly one directory separator (os.sep) following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty. If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.</p>

<p>On Windows, the drive letter is not reset when an absolute path component (e.g., r'\foo') is encountered. If a component contains a drive letter, all previous components are thrown away and the drive letter is reset. Note that since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.</p>

python