I run Run.py
where I am calling File1.py
which is located in another folder 1
. How do I save the output of File1.py
in 1.txt
in the same folder in which it is located and not the folder in which Run.py
is located?
Run.py
is
import subprocess
print(subprocess.run(['python',rf'C:\\Users\\USER\\OneDrive - Technion\\Research_Technion\\Python_PNM\\Sept15_2022\\Test\\1\\File1.py']))
File.py
is
import csv
A=1
B=2
C=A B
print(C)
with open('1.txt', 'w') as f:
writer = csv.writer(f)
print(C)
f.writelines('R' '\n')
f.write(str(C))
CodePudding user response:
You can find the path of the currently running script with the __file__
variable. So something like this would probably work:
import os
current_dir = os.path.dirname(__file__)
filename = os.path.join(current_dir, "1.txt")
with open(filename, "w") as f:
# rest of code goes here
CodePudding user response:
Just add concat the path where the file.py is located to that 1.txt. You can get the path where file.py is located by:
import os
file_py_path = os.path.dirname(os.path.realpath(__file__))
Explore os.path.join() to join paths, this way you will avoid problems related to diff filesystems.