Python issue with writing too local file

lkpat

Executive Member
Joined
Apr 9, 2023
Messages
7,139
Reaction score
5,965
Location
In your head
*heading should read to local file

I have a routine that looks for a file and if it doesn't exist, it creates it, but for some reason, when reading the contents of the file, it's apparently empty. What am I doing wrong?

Code:
import os
if not os.path.isfile('last.txt'):
    outfile = open('last.txt', 'w')
    print ('2023-01-01 00:00:00', file=outfile)
    outfile.close

infile = open('last.txt', 'r')
mytime = infile.readline()
print (mytime)

This basically checks to see if a file (last.txt) exists, and if it doesn't, it creates it and writes a string to it.
When the code is run the first time around (when last.txt does not yet exist), the print (mytime) statement returns an empty string.
When it's run again (last.txt was created the first time it was run and already exists), it's able to read the string that was written to the file.
 
Also, use context managers imo

Python:
with open(path_to_file, 'w', encoding='utf-8') as f_out:
    f_out.write(data_to_write)

This way you don't have to explicitly close files
 
Also, use context managers imo

Python:
with open(path_to_file, 'w', encoding='utf-8') as f_out:
    f_out.write(data_to_write)

This way you don't have to explicitly close files
Done, thanks!
Any idea what's actually wrong with the OP? I mean, theoretically it should work, right? Curiosity more.
 
LOL.... nail -> head.
Thanks for that haha. I do prefer your approach so will use that, ta.

By the way, try something like Pylint, which can help you catch basic issues like this, you can run it on your entire file:

Code:
> pylint print_time.py
************* Module print_time
print_time.py:1:0: C0114: Missing module docstring (missing-module-docstring)
print_time.py:4:14: W1514: Using open without explicitly specifying an encoding (unspecified-encoding)
print_time.py:6:4: W0104: Statement seems to have no effect (pointless-statement)
print_time.py:8:9: W1514: Using open without explicitly specifying an encoding (unspecified-encoding)
print_time.py:4:14: R1732: Consider using 'with' for resource-allocating operations (consider-using-with)
print_time.py:8:9: R1732: Consider using 'with' for resource-allocating operations (consider-using-with)

-----------------------------------
Your code has been rated at 2.50/10

Or alternatively, if you use vscode, just install the extension
 
Last edited:
By the way, try something like Pylint, which can help you catch basic issues like this, you can run it on your entire file:

Code:
> pylint print_time.py
************* Module print_time
print_time.py:1:0: C0114: Missing module docstring (missing-module-docstring)
print_time.py:4:14: W1514: Using open without explicitly specifying an encoding (unspecified-encoding)
print_time.py:6:4: W0104: Statement seems to have no effect (pointless-statement)
print_time.py:8:9: W1514: Using open without explicitly specifying an encoding (unspecified-encoding)
print_time.py:4:14: R1732: Consider using 'with' for resource-allocating operations (consider-using-with)
print_time.py:8:9: R1732: Consider using 'with' for resource-allocating operations (consider-using-with)

-----------------------------------
Your code has been rated at 2.50/10

Or alternatively, if you use vscode, just install the extension

Thanks, that's a great help

One more quick q for the fundis. When working with complex json, is it advisable to deserialize and use custom object classes? It looks pretty time consuming and code intensive, but I guess if it's the better way to go...

Here's the json:
Code:
{
  "events": [
    {
      "end": "2023-04-17T15:30:00+02:00",
      "note": "Stage 6",
      "start": "2023-04-17T11:00:00+02:00"
    },
    {
      "end": "2023-04-17T23:30:00+02:00",
      "note": "Stage 6",
      "start": "2023-04-17T19:00:00+02:00"
    },
    {
      "end": "2023-04-18T05:30:00+02:00",
      "note": "Stage 6",
      "start": "2023-04-18T03:00:00+02:00"
    },
    {
      "end": "2023-04-18T13:30:00+02:00",
      "note": "Stage 6",
      "start": "2023-04-18T11:00:00+02:00"
    },
    {
      "end": "2023-04-18T23:30:00+02:00",
      "note": "Stage 6",
      "start": "2023-04-18T19:00:00+02:00"
    },
    {
      "end": "2023-04-19T07:30:00+02:00",
      "note": "Stage 6",
      "start": "2023-04-19T03:00:00+02:00"
    },
    {
      "end": "2023-04-19T13:30:00+02:00",
      "note": "Stage 6",
      "start": "2023-04-19T11:00:00+02:00"
    },
    {
      "end": "2023-04-19T21:30:00+02:00",
      "note": "Stage 6",
      "start": "2023-04-19T19:00:00+02:00"
    }
  ],
  "info": {
    "name": "Kei Mouth (14)",
    "region": "Eskom Direct, Boksnotfotein, Western Cape"
  },
  "schedule": {
    "days": [
      {
        "date": "2023-04-17",
        "name": "Monday",
        "stages": [
          [
            "19:00-21:30"
          ],
          [
            "11:00-13:30",
            "19:00-21:30"
          ],
          [
            "03:00-05:30",
            "11:00-13:30",
            "19:00-21:30"
          ],
          [
            "03:00-05:30",
            "11:00-13:30",
            "19:00-21:30"
          ],
          [
            "03:00-05:30",
            "11:00-13:30",
            "19:00-23:30"
          ],
          [
            "03:00-05:30",
            "11:00-15:30",
            "19:00-23:30"
          ],
          [
            "03:00-07:30",
            "11:00-15:30",
            "19:00-23:30"
          ],
          [
            "03:00-07:30",
            "11:00-15:30",
            "19:00-23:30"
          ]
        ]
      },
      {
        "date": "2023-04-18",
        "name": "Tuesday",
        "stages": [
          [],
          [
            "19:00-21:30"
          ],
          [
            "11:00-13:30",
            "19:00-21:30"
          ],
          [
            "03:00-05:30",
            "11:00-13:30",
            "19:00-21:30"
          ],
          [
            "03:00-05:30",
            "11:00-13:30",
            "19:00-21:30"
          ],
          [
            "03:00-05:30",
            "11:00-13:30",
            "19:00-23:30"
          ],
          [
            "03:00-05:30",
            "11:00-15:30",
            "19:00-23:30"
          ],
          [
            "03:00-07:30",
            "11:00-15:30",
            "19:00-23:30"
          ]
        ]
      },
      {
        "date": "2023-04-19",
        "name": "Wednesday",
        "stages": [
          [
            "03:00-05:30"
          ],
          [
            "03:00-05:30"
          ],
          [
            "03:00-05:30",
            "19:00-21:30"
          ],
          [
            "03:00-05:30",
            "11:00-13:30",
            "19:00-21:30"
          ],
          [
            "03:00-07:30",
            "11:00-13:30",
            "19:00-21:30"
          ],
          [
            "03:00-07:30",
            "11:00-13:30",
            "19:00-21:30"
          ],
          [
            "03:00-07:30",
            "11:00-13:30",
            "19:00-23:30"
          ],
          [
            "03:00-07:30",
            "11:00-15:30",
            "19:00-23:30"
          ]
        ]
      },
      {
        "date": "2023-04-20",
        "name": "Thursday",
        "stages": [
          [
            "11:00-13:30"
          ],
          [
            "03:00-05:30",
            "11:00-13:30"
          ],
          [
            "03:00-05:30",
            "11:00-13:30"
          ],
          [
            "03:00-05:30",
            "11:00-13:30",
            "19:00-21:30"
          ],
          [
            "03:00-05:30",
            "11:00-15:30",
            "19:00-21:30"
          ],
          [
            "03:00-07:30",
            "11:00-15:30",
            "19:00-21:30"
          ],
          [
            "03:00-07:30",
            "11:00-15:30",
            "19:00-21:30"
          ],
          [
            "03:00-07:30",
            "11:00-15:30",
            "19:00-23:30"
          ]
        ]
      },
      {
        "date": "2023-04-21",
        "name": "Friday",
        "stages": [
          [
            "17:00-19:30"
          ],
          [
            "09:00-11:30",
            "17:00-19:30"
          ],
          [
            "01:00-03:30",
            "09:00-11:30",
            "17:00-19:30"
          ],
          [
            "01:00-03:30",
            "09:00-11:30",
            "17:00-19:30"
          ],
          [
            "01:00-03:30",
            "09:00-11:30",
            "17:00-21:30"
          ],
          [
            "01:00-03:30",
            "09:00-13:30",
            "17:00-21:30"
          ],
          [
            "01:00-05:30",
            "09:00-13:30",
            "17:00-21:30"
          ],
          [
            "01:00-05:30",
            "09:00-13:30",
            "17:00-21:30"
          ]
        ]
      },
      {
        "date": "2023-04-22",
        "name": "Saturday",
        "stages": [
          [],
          [
            "17:00-19:30"
          ],
          [
            "09:00-11:30",
            "17:00-19:30"
          ],
          [
            "01:00-03:30",
            "09:00-11:30",
            "17:00-19:30"
          ],
          [
            "01:00-03:30",
            "09:00-11:30",
            "17:00-19:30"
          ],
          [
            "01:00-03:30",
            "09:00-11:30",
            "17:00-21:30"
          ],
          [
            "01:00-03:30",
            "09:00-13:30",
            "17:00-21:30"
          ],
          [
            "01:00-05:30",
            "09:00-13:30",
            "17:00-21:30"
          ]
        ]
      },
      {
        "date": "2023-04-23",
        "name": "Sunday",
        "stages": [
          [
            "01:00-03:30"
          ],
          [
            "01:00-03:30"
          ],
          [
            "01:00-03:30",
            "17:00-19:30"
          ],
          [
            "01:00-03:30",
            "09:00-11:30",
            "17:00-19:30"
          ],
          [
            "01:00-05:30",
            "09:00-11:30",
            "17:00-19:30"
          ],
          [
            "01:00-05:30",
            "09:00-11:30",
            "17:00-19:30"
          ],
          [
            "01:00-05:30",
            "09:00-11:30",
            "17:00-21:30"
          ],
          [
            "01:00-05:30",
            "09:00-13:30",
            "17:00-21:30"
          ]
        ]
      }
    ],
    "source": "https://loadshedding.eskom.co.za/"
  }
}

Basically:
Code:
events
    |_end
    |_note
    |_start
info
    |_name
    |_region
schedule
    |_days
        |_date
        |_name
        |_stages
            |_[xxxx-xxxx],[xxxx-xxxx]...
I need to be able to iterate through the various items, arrays and array values, parse / perform calculations with he values, etc.
I'd like to avoid third party modules to make the finished app easier to deploy as a standalone script, but I'm open to using modules if it's recommended.

Thanks!
 
Last edited:
Character.ai (competitor to ChatGPT) gave this output:


Pair Programmer
[email protected]

Sure, I can help you fix the code. It looks like you're trying to create a log file called "last.txt." If the file doesn't exist, you create it and write a time stamp to it. If it already exists, you read from it and print the time stamp.
There are a few issues with the code:

1.You don't check if the file opened successfully. You should use a try-except block to catch any exceptions that might occur.

import os
if not os.path.isfile('last.txt'):
outfile = open('last.txt', 'w')
print ('2023-01-01 00:00:00', file=outfile)
outfile.close()

else:
try:
infile = open('last.txt', 'r')
mytime = infile.readline()
except FileNotFoundError:
print("File not found.")
else:
print(mytime)
2. You're not closing the outfile when it already exists. You should wrap the file opening and closing code in a
with block to ensure that it's automatically closed when you're done using it.


if not os.path.isfile('last.txt'):
outfile = open('last.txt', 'w')
print ('2023-01-01 00:00:00', file=outfile)

else:
try:
with open('last.txt', 'r') as infile:
mytime = infile.readline()
except FileNotFoundError:
print("File not found.")
else:
print(mytime)

3. When printing errors, you should always print the entire error message, including the traceback. This will make it easier for you to debug the code.
import os
if not os.path.isfile('last.txt'):
with open('last.txt', 'w') as outfile:
print ('2023-01-01 00:00
 
Top
Sign up to the MyBroadband newsletter
X