Reading a file from Rhythmbox plugin - python

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)

Related

configparser NoSectionError Python

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

I want to open a json file in python but got an error. It said No such file or directory

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/

docx.opc.exceptions.PackageNotFoundError

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.")

How to parse xml from local disk file in python?

I have a code like this :
import requests
user_agent_url = 'http://www.user-agents.org/allagents.xml'
xml_data = requests.get(user_agent_url).content
Which will parse a online xml file into xml_data. How can I parse it from a local disk file? I tried replacing with path to local disk,but got an error:
raise InvalidSchema("No connection adapters were found for '%s'" % url)
InvalidSchema: No connection adapters were found
What has to be done?
Note that the code you quote does NOT parse the file - it simply puts the XML data into xml_data. The equivalent for a local file doesn't need to use requests at all: simply write
with open("/path/to/XML/file") as f:
xml_data = f.read()
If you are determined to use requests then see this answer for how to write a file URL adapter.
You can read the file content using open method and then use elementtree module XML function to parse it.
It returns an etree object which you can loop through.
Example
Content = open("file.xml").read()
From xml.etree import XML
Etree = XML(Content)
Print Etree.text, Etree.value, Etree.getchildren()

Can anyone tell me what error msg "line 1182 in parse" means when I'm trying to parse and xml in python

This is the code that results in an error message:
import urllib
import xml.etree.ElementTree as ET
url = raw_input('Enter URL:')
urlhandle = urllib.urlopen(url)
data = urlhandle.read()
tree = ET.parse(data)
The error:
I'm new to python. I did read documentation and a couple of tutorials, but clearly I still have done something wrong. I don't believe it is the xml file itself because it does this to two different xml files.
Consider using ElementTree's fromstring():
import urllib
import xml.etree.ElementTree as ET
url = raw_input('Enter URL:')
# http://feeds.bbci.co.uk/news/rss.xml?edition=int
urlhandle = urllib.urlopen(url)
data = urlhandle.read()
tree = ET.fromstring(data)
print ET.tostring(tree, encoding='utf8', method='xml')
data is a reference to the XML content as a string, but the parse() function expects a filename or file object as argument. That's why there is an an error.
urlhandle is a file object, so tree = ET.parse(urlhandle) should work for you.
The error message indicates that your code is trying to open a file, who's name is stored in the variable source.
It's failing to open that file (IOError) because the variable source contains a bunch of XML, not a file name.

Categories