2

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!

CommandPromptScreenShot

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()
3
  • 1
    Where did you look for the output file? Did you check the current directory you were in when you ran the script? A relative file path will be relative to the current directory from where you ran the script. Commented Mar 5, 2021 at 18:06
  • Thank you @David ! That was the fix. It was writing the file to where I was running the script. Commented Mar 5, 2021 at 18:21
  • No problem. We have all made that mistake. Commented Mar 5, 2021 at 18:31

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.