Showing posts with label python import os. Show all posts
Showing posts with label python import os. Show all posts

Wednesday, February 24, 2016

Renaming File with Python and Flask

It is sometimes needed to change the name of the file according to your programming needs. Especially if you are working with flask and uploading some file with the help of it. The name of the file we want to upload is often to be changed to our requirements. e.g. I have an employee database , when I want to upload a photo of the employee we might want to change the name of the file to employyeid.jpg format as to find it easily.

Look at the below program -

import os
#Image File Uploading starting 
UPLOAD_FOLDER = 'G:/python flask/microblog/app/Uploded Images/employeephoto' 
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

#app = Flask(__name__)app.config['ALLOWED_EXTENSIONS']=ALLOWED_EXTENSIONS
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

file = request.files.get("employeepic")

if file and allowed_file(file.filename,ALLOWED_EXTENSIONS):
    filename = str(secure_filename(file.filename))
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
    #os.chdir(os.path.join)    extension=filename.split(".")
    extension=str(extension[1])
    source=UPLOAD_FOLDER+"/"+filename
    destination=UPLOAD_FOLDER+"/"+employeeid+"."+extension
    print source+"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"+destination
    os.rename(source,destination)
    flash(file.filename+" saved succesfully")
 
 

Look at the highlighted in red, those are the use of os functions in this program. 
os.path.join() is needed to add the file.filename to the location UPLOAD_FOLDER. Now the 
file can be saved at UPLOAD_FOLDER. If we needed to change the directory then we should 
have used os.chdir() shown in comment section. The next thing was os.rename(source,destination)
which is needed to change the name of the filename to the destination filename. The source 
and destination is described in the previous lines. 

Feautured Post

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element...