How to rename files using python script?

On my plone site, I have hundreds of files (pdf, doc, ...) in the file field of archetype objects. During the import, something went wrong and all the file names are missing. The problem is that when someone wants to open a file because there is no extension, the browser does not always offer to open it using the viewer.

The user must save the file and add the extension to open it.

Is it possible to write a python script to rename all files with the extension depending on the file type?

Thanks.

+4
source share
2 answers

http://plone.org/documentation/manual/plone-community-developer-documentation/content/rename

you have everything you need :)

The important part: parent.manage_renameObject (id, id + "-old")

you can loop over subobjects:

for i in context.objectIds(): obj = context[i] context.manage_renameObject(i, i + ".pdf") 

context is the folder in which you place this script, the folder in which you have all your pdf files

+3
source

The standard library function os.rename(src, dst) will do the trick. This is all you need if you know what the extension should be (for example, all -.pdf files). If you have a mixed package of .doc, .pdf, .jpg, .xls files without extensions, you will need to examine the contents of the file to determine the correct extension using something like python-magic .

 import os for fn in os.listdir(path='.'): os.rename(fn, fn + ".pdf") 
+2
source

Source: https://habr.com/ru/post/1380185/


All Articles