-1

I have a python file, e.g. scan.py which needs to import util.py(in another folder). The util.py file is reading the xml configuration file

config = ET.parse("config.xml")

however, when I run scan.py, I get the error that "No such file or directory: 'config.xml'" how could I solve this kind of problem..?

Nihal
  • 5,262
  • 7
  • 23
  • 41
allencharp
  • 1,101
  • 3
  • 14
  • 31

2 Answers2

2

Relative file paths (like your 'config.xml') are always relative to the directory you're calling the python executable. For instance:

D:\dev\projects\>python myapp.py

If myapp.py imports something from god-only-knows where that's looking for a file named "childfolder/filename.ext", then it's actually looking for D:\dev\projects\childfolder\filename.ext.

If you need your file path to be relative to the script that is looking for it, you need to make it an absolute path. The easiest way to do this is by using __file__, which is a magical variable that contains the absolute path to the script that's running. You can use os.path to do this by getting the directory name of __file__ (the directory your file lives in) then joining it with the config.xml name:

os.path.join(os.path.dirname(__file__), "config.xml")

but pathlib makes this even easier.

# inside D:\dev\projects\myapp.py
configpath = pathlib.Path(__file__).with_name("config.xml")
assert configpath == pathlib.Path(r"D:\dev\projects\config.xml")  # ta-da!
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
0

First you have to make sure both your xml file and your scan.py script are in the same folder.

Then you can basically use the commands:

src = open('config.xml')
parseddoc = parse(src) #to parse the opened file 
Nijat Mursali
  • 930
  • 1
  • 8
  • 20