Radheya
Radheya

Reputation: 821

error importing full path stored in another file

I have two python files. Lets say a.pyand b.py and I am trying to import some paths stored in a.py to b.py.

a.py

parameter_file_path = C:/python-projects/PythonWork/gen.py

trace_file_path = C:/python-projects/PythonWork/gen.asc

b.py

from a import *

After running code in b.py I get error

  File "<string>", line 1, in <module>
  File "C:\python-projects\PythonWork\a.py", line 1
    parameter_file_path = C:/python-projects/PythonWork/gen.py
                           ^
SyntaxError: invalid syntax

What I want:

I want it to just import both variables with path from a.py into b.py without showing any error.

What I tried

I tried changing the way I write this variables in a.py. I use the following code to write information to file

file = open('a.py', 'w+')

file.write('parameter_file_path = {}'.format(str(self.paraName.name.encode('ascii','ignore'))))
file.write('\n')
file.write('\n')

if trace_file:
    file.write('trace_file_path = {}'.format(trace_file.name.encode('ascii','ignore')))

file.close()

self.paraName.name = contains path name to parameter file

trace_file.name = contains path to trace file

I tried writing this as a simple string and also using .encode as in above code but it makes no difference.

I also tried changing C:/python-projects/PythonWork/gen.py to 'C:/python-projects/PythonWork/gen.py' manually in a.py and it works just fine. But even after lots of trying I am not able to store my path in string with single quotes just like above.

Upvotes: 0

Views: 45

Answers (1)

elzell
elzell

Reputation: 2306

If you want a.py to be proper Python syntax you should specify the paths like

parameter_file_path = r'C:/python-projects/PythonWork/gen.py'

The r in front of the string is not necessary here because you only use slashes as path delimiters, but should be used when you write the path with backslashes.

Writing a.py can be done like this:

file.write("parameter_file_path = r'{}'".format(str(self.paraName.name.encode('ascii','ignore'))))

Upvotes: 1

Related Questions