4

On my plone site I have hundreds of files (pdf, doc, ...) in filefield of archetypes objects. Something went wrong during importation and all the filenames are missing. The problem is that when somebody wants to open the file, since the extension is missing, the browser doesn't always propose to open it with a viewer.

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

Can I write a python script to rename all files with an extension depending on the filetype?

Thank you.

user1035648
  • 493
  • 4
  • 7
  • Just a side-note, browsers usually (or primarily) use headers to determine what to do with resource. So having the right extension might not help. Although it might as plone could use it to set correct headers. – rplnt Nov 08 '11 at 13:27

2 Answers2

3

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

you've all you need here :)

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

you can loop over the subobjects doing:

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

context is the folder where you put this script, the folder where you've all your pdfs

Yuri
  • 1,074
  • 5
  • 9
  • it can take some time, I think, over hundreds of file. You've also to find a way to understand if it is a doc or a pdf. – Yuri Nov 08 '11 at 13:34
  • It seems that it renames the id of my file objects but not the filename itself. My filename remains empty. – user1035648 Nov 14 '11 at 18:02
  • the filename should take the name from the object id. Here: http://api.plone.org/Plone/2.1.1/public/Archetypes.Field.FileField-class.html there's a method called setFilename. I think you've to use an external method or a browser view to call it. Search Archetypes/BaseUnit.py, there's an attibute in the field called "filename" which carry the name. setFilename is called when you process the input, that is when you save the file. – Yuri Nov 29 '11 at 14:44
2

The standard library function os.rename(src, dst) will do the trick. That's all you need if you know what the extension should be (e.g. all the files are .pdf). If you have a mixed bag of .doc, .pdf, .jpg, .xls files with no extensions, you'll need to examine the file contents to determine the proper extension using something like python-magic.

import os

for fn in os.listdir(path='.'):
    os.rename(fn, fn + ".pdf")
Dave
  • 3,834
  • 2
  • 29
  • 44