1

I am following Need a minimal Django file upload example. in view.py there is

newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save

Let say I upload the file xyz.csv which make newdoc or docfile as

newdoc=xyz.csv or docfile=xyz.csv

I want to do:

changedoc = xyz.txt

i.e. I want to remove the extension and give it .txt extension

How I can play with it? I just need to extract the name only not the file itself.

Community
  • 1
  • 1
ashir nasir
  • 207
  • 2
  • 6
  • 11

1 Answers1

1

Read the file name from request.FILES['docfile'].name, use os.path.splitext() to get the file name without extension:

docfile = request.FILES['docfile']
filename = os.path.splitext(docfile.name)[0]
newfilename = 'ok_%s.txt' % filename
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • thanks a lot, what if i want to add a prefix (ok_)also, ok_docfile.txt – ashir nasir Sep 22 '13 at 14:03
  • @ashirnasir you are welcome. Just use `newfilename = 'ok_%s.txt' % filename`, updated the answer. – alecxe Sep 22 '13 at 14:05
  • thanks, i know it might be irrelivent to the question, but please advice. in view.py (6th line from last) i am trying to replace documents=Document.objects.all() with my newfilename but get error. i am trying to to insted of xyz.csv, link to ok_xyz.txt appears in the 127.0.0.1:8000/myapp/list – ashir nasir Sep 22 '13 at 14:46