So, im new to coding and im making a registration system for a fictional hospital, that gets the user name, the procedure they had and the date, after that it sum some days to it( to calculate return) and then write on a .txt file, but the write part is not working is not working, how can i solve it? sorry that the prints and variables are on portuguese.
def cadastrar(arq, nomep , proc , x, y, z, w):
datas = datetime.strptime(w, '%Y-%m-%d')
l = 0
m = 0
n = 0
o = 0
p = 0
try:
a = open(arq, 'r ')
for linha in a:
dados = linha.split(';')
if dados[1] in ['Procedimento X']:
l = datas \
timedelta(days = 15)
m = datas \
timedelta(days = 152)
n = datas \
timedelta(days = 304)
o = datas \
timedelta(days = 456)
try:
a.write(f'{nomep};{proc};{x}-{y}-{z}\n;{l};{m};{n};{o}')
except:
print('\033[31mErro ao escrever.\033[m')
else:
print(f'\033[92m{nomep} foi cadastrado com sucesso.\033[m')
a.close()
finally:
print('')
I want it to write on the txt file but suddently it just stopped working and idk why.
CodePudding user response:
try changing
a = open(arq, 'r ')
to
a = open(arq, 'w ')
CodePudding user response:
Try using context manager for this, also repalace r
with w
, and then you don't need the close
in finally
and read the lines:
from datetime import datetime, timedelta
def cadastrar(arq, nomep , proc , x, y, z, w):
datas = datetime.strptime(w, '%Y-%m-%d')
l = 0
m = 0
n = 0
o = 0
p = 0
try:
with open(arq, 'w ') as f:
for linha in f.readlines():
dados = linha.split(';')
if dados[1] in ['Procedimento X']:
l = datas \
timedelta(days = 15)
m = datas \
timedelta(days = 152)
n = datas \
timedelta(days = 304)
o = datas \
timedelta(days = 456)
try:
f.write(f'{nomep};{proc};{x}-{y}-{z}\n;{l};{m};{n};{o}')
except:
print('\033[31mErro ao escrever.\033[m')
else:
print(f'\033[92m{nomep} foi cadastrado com sucesso.\033[m')
except Exception as e:
print(f"Error writing to file - {e}")
finally:
print("Finished ... ")