Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  3] [ 0]  / answers: 1 / hits: 3207  / 2 Years ago, tue, october 11, 2022, 10:42:32

I have a folder called X which inside has many folders and sub-folders. I want to search in all of the folders inside X and find a specific document type. For example xlsx and transform each file into an xls file. In this case I need to use the libreoffice convert option like libreoffice --headless --convert-to xls but here is the catch. After conversion each converted file should be in the same folder as the original xlsx file.



Example:



X/
Folder 1/
Folder 2/
Folder 2.1/file.xlsx
Folder 3/
Folder 4/
Folder 4.1/anotherFile.xlsx


After conversion:



X/
Folder 1/
Folder 2/
Folder 2.1/file.xls
Folder 2.1/file.xlsx
Folder 3/
Folder 4/
Folder 4.1/anotherFile.xls
Folder 4.1/anotherFile.xlsx


The new xls* in this case, will be converted on the same folder as the original xlsx. This will be done inside all sub-folders and to all xlsx that are found.


More From » libreoffice

 Answers
1

Here is a python script that does as you described.



For convenience reasons, to be used with other conversion commands, I defined the filepath+name and the destination before entering it in the convert command. That also makes it easy to change the destination to something else than the file's current directory (if for some reason you might need that).



note: In some cases (like mine), the command



libreoffice --headless --convert-to xls


only works when using sudo. If that is the case, you need to change ownership of ~/.config with the command:



sudo chown -R --reference="$HOME" ~/.config


as described here.



The script:



#!/usr/bin/python3

convert_dir = "/path/to/folder/tobeconverted"
import os
import subprocess

for root, dirs, files in os.walk(convert_dir):
for name in files:
if name.endswith(".xlsx"):
# filepath+name
file = root+"/"+name
destination = root
subprocess.Popen(["libreoffice", "--headless", "--convert-to", "xls", file, "--outdir", destination])
else:
pass


Copy it into an empty textfile, replace the directory in the top of the file, save it with the .py extension and run it with the command:



python3 /path/to/scrip/script.py


But I am pretty sure you know that. :)


[#25217] Wednesday, October 12, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
azaaburge

Total Points: 266
Total Questions: 85
Total Answers: 109

Location: Djibouti
Member since Sat, Oct 29, 2022
2 Years ago
azaaburge questions
Thu, Jun 2, 22, 23:28, 2 Years ago
Sun, Oct 17, 21, 05:20, 3 Years ago
Fri, Jun 25, 21, 16:22, 3 Years ago
;