Reputation: 23
I am trying to run a python file at C:\Users\maxwe\PATH TO FILE\testScripts\writeToFile.py from outside of the testScripts folder.
Notice the below command prompt screen shot (I included the version to show that the python command is resolving to something). The writeToFile.py script seems to execute since I receive no errors but it does not write Hello World to the file like I want it to.
I can run the script from within the testScripts folder and it works as expected but the end goal with this project is to run the python script from a Java Spring API that will reside outside that source folder by running something like Runtime.getRuntime().exec("python C:\Users\maxwe\PATH TO FILE\testScripts\writeToFile.py"); so "cd"ing into the folder and running the script doesn't help much.
Thanks in advance!
Here is the python file as well:
# -*- coding: utf-8 -*-
"""
Created on Feb 25 2021
@author: maxwe
"""
def run():
file1 = open("log.txt","w")
file1.write("Hello World")
file1.close()
run()
Upvotes: 2
Views: 693
Reputation: 96
There are more "pythonic" ways of doing this using os and redefining your directory. But for simplicity and to directly answer your question you need to define the absolute path where this file can be found.
path = 'C:\\Users\\maxwe\\Desktop\\personal_projects\\water_robot\\log.txt'
with open(path, 'w') as f:
f.write('Hello World')
f.close()
Upvotes: 1