-1

Script will pick the xml file from XML folder and parse it, it is running great when I run .py file directly. But, when I call the .py using .bat file I am getting below errors.

XML.bat

@ECHO OFF
REM A batch script to execute a Python script
SET PATH=%PATH%;C:\Users\%USERNAME%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.6
py GET_XML.py
PAUSE

Python snippet for getting file name under xml folder

import os
pathx = (os.path.dirname(__file__)+str('\\xml\\'))
list1 = os.listdir(pathx)
#GET Folder
#print(pathx)
paths = (''.join(map(str,list1)))
#GET Files inside Folder
#print(paths)
#Insert in xml parse
tree = ET.parse(paths)
root = tree.getroot()

Error

enter image description here

Directory Structure

Python(folder)   
  +GET_XML.py
  +XML.bat
  +XML (folder)
      +1231.xml
Prime
  • 3,530
  • 5
  • 28
  • 47

1 Answers1

1

It is more reliable to join paths using os.path.join, it will take care of escaping the characters and pick the path separator for your system. Try to use the following line:

pathx = (os.path.join(os.path.dirname(__file__), 'xml'))
Joe
  • 6,758
  • 2
  • 26
  • 47
  • In this case, `os.path.dirname(__file__)` returns an empty string, because `__file__` is relative to the working directory. In this case `os.path.join` will simply return "xml", which is also relative to the working directory. However, any script that uses `__file__` should *immediately* get the fully-qualified path when loading, e.g. `script_path = os.path.abspath(__file__)`, in case the working directory gets changed later. – Eryk Sun Feb 12 '18 at 06:22
  • I found what you mean: https://stackoverflow.com/a/7116925/7919597, it depends it if the module is in `sys.path`, but I also found that starting from Python 3.4 it is always absolute: https://docs.python.org/3.4/whatsnew/3.4.html#other-language-changes – Joe Feb 13 '18 at 12:51
  • I was talking about a script, not an imported module. For modules, if `__file__` is set, it should be absolute in Python 3. For scripts it depends on the path passed on the command line. – Eryk Sun Feb 13 '18 at 17:15