1

I am trying to change an extension for a file, and I got two options.

os.path.splitext(os.path.basename(g_filename))[0] + ".new"

os.path.basename(g_filename).split('.')[0] + ".new"

Both gives the same output. So i am getting a new file called oldfile.new from oldfile.old

No possibility of having too many '.' in the file name.

Which is better of these two? What is the thumb rule (if any)?

Srini V
  • 11,045
  • 14
  • 66
  • 89

2 Answers2

4

As you implement them, they are different. Use correct one:

>>> os.path.splitext(os.path.basename('a.b.c'))[0] + '.new'
'a.b.new'
>>> os.path.basename('a.b.c').split('.')[0] + ".new"
'a.new'

Update

One can replace split call with rsplit(..., 1), and result will be similar to splitext:

>>> os.path.basename('a.b.c').rsplit('.', 1)[0] + ".new"
'a.b.new'

But difference between functions still exsits, as splitext treats filenames starting with a dot as having no extension, most probably since those are special for unix based os:

>>> os.path.splitext(os.path.basename('.a'))[0] + '.new'
'.a.new'
>>> os.path.basename('.a').rsplit('.', 1)[0] + '.new'
'.new'
alko
  • 46,136
  • 12
  • 94
  • 102
2

The first one is the better of the two.

The second one would get tripped up if the filename had two or more periods in it.

synthesizerpatel
  • 27,321
  • 5
  • 74
  • 91