Member Avatar for Member #616967
Member #616967

I had recently made a .bat file that read a couple lines from file.txt and assigned them as variables then went through the execution of the bat which ended up deleting the original file.txt and writing the new values to a new file.txt.

Now I want to convert this to a .py.

The text file looked like:

ABC
1234
ZXY
4321

The label only being 3 characters and the time in the format of hhmm. and can be anywhere between 0000 and 9959

The .bat assigned them to their own var - then asked for the user to add an additional time in the format of hhmm.

Once the minutes hit +59 it would carry over to the next hour and add the remaining minutes.

Set the variable to the new amount and printed to the file.txt with the new times.


Now being that I haven't worked with python much and haven't looked at in in about 2 years and I remember almost nothing I am having a hard time trying to get started. I'll post what I have so far, but it is far from doing what I want and far from complete,

It can read from a text file with the variables pretty much already set cause of what I found on another post, but doesn’t set it in the correct format (hhmm), asks user for additional hours, again not the right format, and then prints to screen what has been added.

#!/usr/bin/python3.2

##Variables
for line in open('File.txt'):
    exec('%s = %s' % tuple(line.split(':', 1)))

x = 'Current '+sec1+' Hours:'+str(h1)
y = 'Current '+sec2+' Hours:'+str(h2)  

##Add hours
print (x)
print (y)

q = input('Add additional hours? ')
if q == 'n':
    quit()
if q == 'y':

st1 = 'Enter additional time for '+sec1+'(hhmm): '
st2 = 'Enter additional time for '+sec2+'(hhmm): '

Ah1 = int(input(st1))
Ah2 = int(input(st2))


Th1 = h1 + Ah1
Th2 = h2 + Ah2

print (Th1)
print (Th2)

And the text file looks like:

sec1: 'ABC'
sec2: 'ZXY'
h1: 0000
h2: 0000

What would be even better is if there was some way to just keep all internal of the single .py but don't know if that’s possible to rewrite over the variables and start up again with the new values - its probably not worth the effort if it is.


I can also post some of the .bat if that may give you a better idea of what I am trying to accomplish.

Any direction and help is appreciated.

Dani AI

Generated

The simplest, robust fix is to stop using exec, parse the file as key:value pairs, convert stored hhmm strings into total minutes, add the extra minutes, then convert back to hhmm (carry handled by integer division/mod). This avoids the pitfalls in the original approach (unsafe exec, treating hhmm like a plain integer, no minutes overflow handling). The snippet below shows a safe, reusable pattern: parse the file, validate hhmm input (minutes must be < 60), add, and write the updated values back while preserving other lines. This directly addresses 's need to carry minutes into hours and keep the file updated.

#!/usr/bin/env python3

from pathlib import Path

def parse_kv(path):
    lines = path.read_text().splitlines()
    kv = {}
    line_idx = {}
    for i, line in enumerate(lines):
        if ':' not in line:
            continue
        key, val = line.split(':', 1)
        kv[key.strip()] = val.strip()
        line_idx[key.strip()] = i
    return lines, kv, line_idx

def hhmm_to_minutes(s):
    s = s.strip()
    if not s.isdigit() or len(s) < 3:
        raise ValueError("bad hhmm")
    h = int(s[:-2])
    m = int(s[-2:])
    if m >= 60 or h < 0:
        raise ValueError("bad hhmm")
    return h * 60 + m

def minutes_to_hhmm(total):
    h, m = divmod(total, 60)
    return "{:02d}{:02d}".format(h, m)

p = Path('File.txt')
lines, kv, idx = parse_kv(p)

pairs = []
for k in sorted(kv.keys()):
    if k.startswith('sec') and k[3:].isdigit():
        n = k[3:]
        hkey = 'h' + n
        if hkey in kv:
            label = kv[k].strip("'\"")
            pairs.append((label, hkey))

for label, hkey in pairs:
    try:
        cur_min = hhmm_to_minutes(kv[hkey])
    except ValueError:
        print("Stored time for {} looks bad: {}".format(label, kv[hkey]))
        continue
    print("Current {}: {}".format(label, minutes_to_hhmm(cur_min)))
    add = input("Add additional time for {} (hhmm, Enter to skip): ".format(label)).strip()
    if not add:
        continue
    add_min = hhmm_to_minutes(add)
    kv[hkey] = minutes_to_hhmm(cur_min + add_min)

for k, v in kv.items():
    if k in idx:
        lines[idx[k]] = "{}: {}".format(k, v)
p.write_text("\n".join(lines) + "\n")

Troubleshooting notes: always back up the file before writing. Validate inputs (reject minute parts >= 60). If you plan to expand use or add fields, store data in JSON or an INI file instead of ad-hoc key:value text — it's easier to read and safer than editing the script itself. Editing the script to store runtime values is possible but fragile; a separate data file is the recommended pattern.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.