I wrote a Python script to generate XML log files but every time I run it, it is saved/written in the same folder/path as the script itself.
Here is a simplified version of it:
import xml.etree.cElementTree as ET
root = ET.Element("LOG")
Child_1 = ET.SubElement(root, "CHILD1")
Child_1.text = "I am child 1"
tree = ET.ElementTree(root)
tree.write("log_file.xml")
However, I want to save/write it in a specific folder. What is the simplest way to do it? Thanks.
You can get the dir like this:
import os
path = os.path.join("C:\\", "Users", os.getlogin(), "Desktop","log_file.xml")
Then you can just do this:
tree.write(path)
Related
Here is my example.
Ex:
I have a folder that contains another 3 folders (FoldA, FoldB, and FoldC), a .txt file, and a .png file.
I have the following working code which works to print the contents a folder or directory.
import pathlib
rd = pathlib.Path("E:\\Location\\MainFolder")
for td in rd.iterdir():
print(td)
The output is:
E:\Location\MainFolder\FoldA
E:\Location\MainFolder\FoldB
E:\Location\MainFolder\FoldC
E:\Location\MainFolder\image.png
E:\Location\MainFolder\text.txt
Does anyone know a quick way to only print the folders and not any other file type (.txt, .bmp, .png, etc.)? I've tried using .is_dir but it still prints everything.
Thanks in advance!
probably you did if td.is_dir with is a function, so you need to execute it like this:
import pathlib
rd = pathlib.Path(".")
for td in rd.iterdir():
if td.is_dir():
print(td)
Kinda common problem with pathlib at beginning :)
Parsing out tags of an .XML file gives additional hyperlink.
I'm trying to read data of a .mzXML file, that is build like a common .XML file.
Printing out the tags is giving me an additional hyperlink of the classification beyond in the "header".
my mzXML file:
<?xml version="1.0" encoding="ISO-8859-1"?>
<mzXML xmlns="http://sashimi.sourceforge.net/schema_revision/mzXML_2.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://sashimi.sourceforge.net/schema_revision/mzXML_2.1 http://sashimi.sourceforge.net/schema_revision/mzXML_2.1/mzXML_idx_2.1.xsd">
<msRun scanCount="1">
my python code:
import xml.etree.cElementTree as ET
tree = ET.parse('data.mzXML')
root = tree.getroot()
print(root[0].tag)
the expected output is
msRun
the actual output is
{http://sashimi.sourceforge.net/schema_revision/mzXML_2.1}msRun
I think you can solve this problem in a "non-canonical" way. I tried to run your code with a little changes (i suggest you to learn and use lxml, is more powerfull than the standard python library for xml, and if you're going to use big and nested files you should consider it):
from lxml import etree as ET
tree = ET.parse('data.mzXML')
root = tree.getroot()
print(root[0])
The result was
<Element {http://sashimi.sourceforge.net/schema_revision/mzXML_2.1}msRun at 0x7ff99afa9e88>
So, the full tag of your file is, as expected, {http://sashimi.sourceforge.net/schema_revision/mzXML_2.1}msRun. You can use, if this problem is reiterated in the dataset, the following code:
from lxml import etree as ET
tree = ET.parse('data.mzXML')
root = tree.getroot()
tag = root[0].tag.split('}')
print(tag[1])
And your output will be as expected. This is a very specific solution, but if all the dataset is affected by this problem, it could be a solution.
I've found similar questions to this but can't find an exact answer and I'm having real difficulty getting this to work, so any help would be hugely appreciated.
I need to find a XML file in a folder structure that changes every time I run some automated tests.
This piece of code finds the file absolutely fine:
import xml.etree.ElementTree as ET
import glob
report = glob.glob('./Reports/Firefox/**/*.xml', recursive=True)
print(report)
I get a path returned. I then want to use that path, in the variable "report" and look for text within the XML file.
The following code finds the text fine IF the python file is in the same directory as the XML file. However, I need the python file to reside in the parent file and pass the "report" variable into the first line of code below.
tree = ET.parse("JUnit_Report.xml")
root = tree.getroot()
for testcase in root.iter('testcase'):
testname = testcase.get('name')
teststatus = testcase.get('status')
print(testname, teststatus)
I'm a real beginner at Python, is this even possible?
Build the absolute path to your report file:
report = glob.glob('./Reports/Firefox/**/*.xml', recursive=True)
abs_path_to_report = os.path.abspath(report)
Pass that variable to whatever you want:
tree = ET.parse(abs_path_to_report )
We have the full path of the file:
/dir1/dir2/dir3/sample_file.tgz
Basically, I would like to end up with this string:
dir3/sample_file.tgz
We can solve it with regex or with .split("/") and then take and concatenate the last two items in the list.....but I am wondering if we can do this more stylish with os.path.dirname() or something like that?
import os
full_filename = "/path/to/file.txt"
fname = os.path.basename(full_filename)
onedir = os.path.join(os.path.basename(os.path.dirname(full_filename)), os.path.basename(full_filename))
no one ever said os.path was pretty to use, but it ought to do the correct thing regardless of platform.
If you're in python3.4 (or higher, presumably), there's a pathlib:
import os
import pathlib
p = pathlib.Path("/foo/bar/baz/txt")
onedir = os.path.join(*p.parts[-2:])
The project folder hierarchy looks like
ProjectName
->src
->Project.sikuli
->myFile.py
->config.txt
Now, I have all the settings variables being stores in my config.txt and I'm using ConfigParser to fetch the values from it. The reason why I'm using this config file here is that, when this sikuli script is moved to another machine for running I can just change the values in it (like paths, username, password) rather than editing the main python script 'myFile.py'.
But the issue I'm encountering now is that I don't want the config file to be placed some where outside the project so that in my script when I try to fetch the values from it, I don't have to mention the absolute path again in the myFile.txt like:
configParser = ConfigParser.RawConfigParser()
configfilePath = r'D:\MyWorkspace\ProjectName\src\Project.sikuli\config.txt'
Instead I want to have the relative path here so that while migrating the project from machine to machine I don't have to do any manipulations in the main script 'myFile.py'
So what I'm trying to achieve is like:
I should be able to refer the config.txt file by giving it's relative path:
configfilePath = r'D:\MyWorkspace\ProjectName\src\Project.sikuli\config.txt'
If it's going to be kept in the same folder as myFile.py, then in that Python script you could use something like this:
configfilePath = os.path.join(os.path.dirname(__file__), 'config.txt')
The best way to do this is to put the file inside your .sikuli bundle, just as you have done in your example, and then get the path to your file like this:
configFilePath = os.path.join(getBundlePath(), 'config.txt')
I know you can fetch variables and value from a python file by importing it...
import config
I would put it in the root repertory of the project
First, get the path of the currently executed python script:
myPath = os.path.abspath(os.path.dirname(sys.argv[0]))
and then do a join of myPath and 'config.txt'
configfilePath = os.path.join(myPath, 'config.txt')