Home > front end >  Create Directory of Files
Create Directory of Files

Time:03-06

I am wanting to run a python script every hour to create a .txt file. I would like for python to create files such as:

file1.txt file2.txt

and so on but can't figure out how to do it - any suggestions?

CodePudding user response:

As mentioned by Leo, assuming you are on Linux, you should write a cronjob to run your script hourly. An example cron expression pulled from my crontab is:

0 8,16 * * * /your/python/path your_python_script.py

This expression runs the specified script at 8AM and 4PM every day. To run your script hourly, you can replace 0 8,16 * * * with @hourly.

To play around with writing cron expressions I found this site useful: Crontab.guru

For more detail on using crontab and troubleshooting issues, this article helped me: JC Chouinard

CodePudding user response:

You import these libraries:

import datetime
import os

Here you will set the number of the initial name of the first saved .txt:

num = 0

And here is an infinite loop, which it checks if the file already exists in the folder. If it exists, it skips while to test if the next file exists (this avoids adding characters to it), if it doesn't exist, it creates the next file with the data from that time. The while will repeat itself every 3600 seconds, which is equivalent to 1h:

while 1:
    # Check if the file already exists in the folder, if it exists, it skips while. 
    # If it doesn't exist, it creates another one to write
    if os.path.isfile(f"arquivo{num}.txt"):
        num  = 1
        continue
    else:
        # Open/Create the file
        arquivo = open(f"arquivo{num}.txt", "a", encoding="utf-8")
        # Write something inside the file
        arquivo.write("Write what you want")
        # Close the file
        arquivo.close()
        print(f"Saved the file: arquivo{num}.txt")
        # Adds  1 to the variable num
        num  = 1
        # Wait 1h to create another file
        sleep(3600)
  • Related