I try to use docxtpl library. docxtpl Use example from documentation:
from docxtpl import DocxTemplate
doc = DocxTemplate("my_word_template.docx")
But there is an error Package not found at '%s'" % pkg_file. If I do this
import os.path
if os.path.isfile('my_word_template.docx'):
print ("File exist")
It is print File exist. File in the same directory as script. Also I tried to use absolute path to file, but that didn't help. In a source I found a place which calls this exception link. How can I fix it?
It probably indicates that the file is not a .docx file. Could you, please, check this file using function is_zipfile from module zipfile?
Try using python-docx by installing it with pip install python-docx.
Then, in you file, write something like this :
try:
document = docx.Document('your_doc_name.docx')
except:
document = docx.Document()
document.save('your_doc_name.docx')
print("Previous file was corrupted or didn't exist - new file was created.")
Related
I have made a config file named "config.cfg" that's on the same folder of my .py file.
My config file is like this:
[NetAccess]
host=localhost
port=3306
[Credentials]
username=myuser
password=mypass
[Database]
name=mydb
in my .py file I have this code:
import configparser
config = configparser.ConfigParser()
config.read('config.cfg')
__DBMSuser = config.get('Credentials', 'username')
__DBMSpsw = config.get('Credentials', 'password')
When I launch my program, I receive this error:
configparser.NoSectionError: No section: 'Credentials'
Can someone help me?
I've solved it. My code was correct, and the .cfg file was correctly saved in the folder of my program, but because of other parts of my code, my current directory changed to "C:/Windows/Service32". Not reading the file, I had not error until I was trying to read the sections, so I got NoSectionError.
To solve it, I've choice a standard folder (in AppData) where to save my file and read it and then I've used the absolute path.
Your code is working for me. Most likely the issue is reading the config file itself. Config Parser's read method is configured to fail silently if it fails to find or read the file, but the read function returns a read_ok boolean flag. Use it to check if the read was successful:
import configparser
config = configparser.ConfigParser()
filename = 'config.cfg'
read_ok = config.read(filename)
if read_ok:
__DBMSuser = config['Credentials']['username']
__DBMSpsw = config['Credentials']['password']
else:
print(f'Could not read file {filename}')
There is no mistake in your code, cuz it works for me.
I think there is some small error with file:
Make sure your file is in same directory as python file
Have you saved your file? maybe you forgot to press ctrl+s
If even that's not working for you, try another version of Python
enter image description here
I wrote the code like this:
intents = json.loads(open('intents.json').read())
Check your intents.json file is in the same folder on which you python file is.
you can use, for example, the os builf-in module to check on the existence of file and os.path for path manipulation. Check the official doc at https://docs.python.org/3/library/os.path.html
import os
file = 'intents.json'
# location of the current directory
w_dir = os.path.abspath('.'))
if os.path.isfile(os.path.join(w_dir, file)):
with open(file, 'r') as fd:
fd.read()
else:
print('Such file does not exist here "{}"...'.format(w_dir))
You can try opening the file using the normal file operation and then use json.load or json.loads to parse the data as per your needs. I may be unfamiliar with this syntax to the best of my knowledge your syntax is wrong.
You can open the file like this:
f = open(file_name)
Then parse the data:
data = json.load(f)
You can refer to this link for more info and reference
https://www.geeksforgeeks.org/read-json-file-using-python/
I've looked up several SO and other web pages but I haven't found anything that works.
The script I wrote, opens a docx, changes some words and then saves it in a certain folder as a docx. However, I want it to save it as a pdf but I don't know how to.
This is an example of the code I'm working with:
# Opening the original document
doc = Document('./myDocument.docx')
# Some code which changes the doc
# Saving the changed doc as a docx
doc.save('/my/folder/myChangedDocument.docx')
The things I tried to do for it to save as a pdf:
from docx2pdf import convert
# This after it was saved as a docx
convert('/my/folder/myChangedDocument.docx', '/my/folder/myChangedDocument.pdf')
But it says that Word needs permission to open the saved file and I have to select the file to give it the permission. After that, it just says:
0%| | 0/1 [00:03<?, ?it/s]
{'input': '/my/folder/contractsomeVariable.docx', 'output': '/my/folder/contractsomeVariable.pdf', 'result': 'error', 'error': 'Error: An error has occurred.'}
And I tried to simply put .pdf instead of .docx after the document name when I saved it but that didn't work either as the module docx can't do that.
So does someone know how I can save a docx as a pdf using Python?
you can use docx2pdf by making the changes first and then coverting.
Use pip to install on mac (I am guessing you already have it but it is still good to include).
pip install docx2pdf
Once docx2pdf is installed, you can your docx file in inputfile and put an empty .pdf file in outputfile.
from docx2pdf import convert
inputFile = "document.docx"
outputFile = "document2.pdf"
file = open(outputFile, "w")
file.close()
convert(inputFile, outputFile)
A simple way, you can use libreoffice
Ref: https://www.libreoffice.org/get-help/install-howto/macos/
And script sample:
def convert_word_to_pdf_local(folder, source, timeout=None):
args = [
LIBREOFFICE_BINARY_PATH,
'--headless',
'--convert-to',
'pdf',
'--outdir',
folder,
source,
]
if check_libreoffice_exists() is False:
raise Exception('Libreoffice not found')
process = subprocess.run(
args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout
)
filename = re.search('-> (.*?) using filter', process.stdout.decode())
if filename is None:
raise Exception('Libreoffice is not working')
else:
filename = filename.group(1)
pdf_file = open(filename, 'rb')
return pdf_file
def check_libreoffice_exists():
s = os.system(f'{LIBREOFFICE_BINARY_PATH} --version')
if s != 0:
return False
return True
I am learning Python and related modules. Here are my scripts.
import tarfile
from six.moves import urllib
data_path = "./datasets/housing/"
file = "housing.tgz"
data_path_file = data_path + file
tar_file = tarfile.open(data_path_file)
# tested following script, failed
tar_file = tarfile.open(data_path_file,'r')
# end test
tar_file.extractall(path=data_path_file)
I hope my scripts can unzip the tgz file and write into a new file. I always received following error messages:
raise ReadError("file could not be opened successfully")
tarfile.ReadError: file could not be opened successfully
I checked the path and file name. No errors exist. Any correction and further help would be highly appreciated.
In my plugin for Rhythmbox I need to read data from xml file. The xml file is the same as the script. I read the file like this :
from xml.dom.minidom import parse
doc = parse('sites.xml')
I get an error saying that the file is not found. I figured out that the script look in home folder not in the /usr/lib/rhythmbox/plugins/myfoder/. Is it an error of my script or just a limit of Rhythmbox?
Thanks.
Try to add direct address.
import os
from xml.dom.minidom import parse
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
xmlfile = os.path.join(BASE_DIR,'sites.xml')
doc = parse(xmlfile)