Python Forum
Writting to file from if/else statement
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Writting to file from if/else statement
#1
The original code is here.

The goal of this code is to have it change the two-letter code every day and write it to the file.

This is the problem code. Specifically lines 43 - 45.
import datetime
import os.path
import random
import string


DATE = datetime.datetime.now()
DAY = DATE.day

def transfer_file():
    """Check if file exists."""
    if os.path.exists("transfer.txt"):
        return
    else:
        with open("transfer.txt", "w") as file:
            return


def code_file():
    """Check if file exists."""
    if os.path.exists("code.txt"):
        return
    else:
        with open("code.txt", "w") as file:
            return

def set_expiration():
    """Sets date format and adds a day."""
    expires = f"{DATE.month}/{DAY + 1}/{DATE.year}"
    return expires

def set_code():
    """Sets random two letter code."""
    letters = string.ascii_uppercase
    code_1 = random.choice(letters)
    code_2 = random.choice(letters)
    day_code = f"{code_1}{code_2}"

    with open("code.txt", "r") as file:
        code = "".join(file.readlines())
        print(code)

    if str(DAY) not in set_expiration():
        with open("code.txt", "w") as file:
            file.write(day_code)
    else:
        return "".join(code)

transfer_file()
code_file()
set_code()
First I don't understand why it won't write to the file on the first run unless I change line 43 to if str(DAY) in set_expiration():.
If I leave the "not" out of line 43 it writes a different code on every run as expected. But if I add
the "not" to line 43 it will change the code on the first run but not on any runs after that no matter how I change str(DAY). I usually change it by taking the + 1 out of line 29. expires = f"{DATE.month}/{DAY + 1}/{DATE.year}"
Why does it ignore my changes?
Reply
#2
If you run your code today it basically does:

"Is 19 in 20/11/2019?" --> True --> Write the file.

"Is not 19 in 20/11/2019?" --> False --> Does not write the file.

So it makes sense that it does not write it when you add the NOT as you can find 19 in the year of "expires".
Reply
#3
@baquerik I hadn't considered that. This code will break on the 19 and 20 of every month in 2019. I need to make it more specific.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  writting python output to a csv file drifterf 1 1,681 Jul-19-2019, 04:07 AM
Last Post: micseydel
  problems with writting a text file sunny 6 3,720 Feb-24-2019, 10:52 PM
Last Post: Larz60+
  Writting system comand into a file. Mike Ru 2 3,702 May-29-2017, 12:40 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020