Search code examples
pythonfiletextboot

Creating a text file using a python script that runs in background on Raspberry Pi


I'm having a problem about the topic in the title. I created a python script on the directory /home/pi/ and it starts running on the background when the Raspberry Pi is booted. It's duty is this:

When I push a button that is connected to one of the GPIO's, it will create a folder in it's own directory, then create a text file called 'fileName.txt' at the directory /home/pi/; and write the name of the folder it just created, in this text file. Everything goes fine until the 'create a text file' part. I boot the Raspberry Pi, then I push the button. The script creates the folder that I want, but after that, it doesn't create the text file. Since it runs in background, I can't see the error on the terminal that may explain the problem. After that, I tried starting the script manually to see the error message; however, this time it worked perfectly well. It created the text file and wrote the name of the folder in it.

This is the simple code that I use to create the file:

text_file = open("folderName.txt", "w")
text_file.write("%s" %folderName)
text_file.close()

Anyone knows how to solve it?


Solution

  • It is probably creating the file in the wrong folder. Try specifying the absolute path where you want to create the file, or discover it inside the script, like the example below:

    import os 
    cwd = os.path.dirname(os.path.abspath(__file__)) 
    text_file = open(os.path.join(cwd, "folderName", "textFile.txt"), "w")
    

    Also, to test a script that is running in background, you can write debug messages to a log file in /var/log (might need root permission) or /tmp, either using the Logging module with a FileHandler, or using the open built-in function.