Posts: 7
Threads: 2
Joined: Oct 2016
Oct-13-2016, 06:58 PM
(This post was last modified: Oct-13-2016, 08:20 PM by Yoriz.)
Lógica para converter um número inteiro para ANO/MÊS
Pessoal, Boa tarde.
Preciso de uma ajuda. Minha dúvida nem é na sintaxe em si, mas em lógica mesmo. Sozinho não to conseguindo resolver.
Preciso criar Arquivos com nome ("DC" + anoAtual + Mes). ex: DC201610, somar 1 ano se passar do mês 12 e ir incrementando o mês até 12
O usuário entra com 2 entradas.
- Número de meses para gerar
- Mes de inicio de 1..12
Eu já to gerando os arquivos, e criando os nomes. Mas só funciona se o usuario de o mês de inicio o mês 01 = Janeiro. porque ele vai até 12 e volta para 01.
O problema está se o usuário começa no mês 10 e precisa criar 5 meses(Arquivos) por exemplo.
Como deveria ficar: DC201610 Como ele está criando: DC201610
DC201611 DC201611
DC201612 DC201612
DC201701 DC201613
DC201702 DC201614
Alguém pode me ajudar? :wall:
Translation
Staff, Good afternoon.
I need help. My question is not in the syntax itself, but even in logic. Alone not getting to solve.
I need to create files with the name ("DC" + anoAtual + Mes). eg DC201610, add one year to spend the month 12 and go up to 12 incrementing the month
The user enters 2 entries.
- Number of months to generate
- Start Month 1..12
I have to generate the files, and creating names. But it only works if the User of the beginning of the month month = January 01. because it goes to 12 and back to 01.
The problem is if the user begins the month 10 and need to create five months (Files) for example.
As it should be:
Output: DC201610
DC201611
DC201612
DC201701
DC201702
as it is creating:
Output: DC201610
DC201611
DC201612
DC201613
DC201614
Can someone help me? :wall:
Posts: 1,298
Threads: 38
Joined: Sep 2016
It would help greatly if your post were in English. The only thing I understood was :wall:
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Posts: 2,342
Threads: 62
Joined: Sep 2016
<Moved to coding help.>
Code in the post would be nice too.
Posts: 2,953
Threads: 48
Joined: Sep 2016
Windows, Max OS X or Linux?
Posts: 2,342
Threads: 62
Joined: Sep 2016
We're not going to do your work for you: what have you tried?
Posts: 1,298
Threads: 38
Joined: Sep 2016
Please post the code that you have so far.
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Posts: 7
Threads: 2
Joined: Oct 2016
Oct-17-2016, 12:40 PM
(This post was last modified: Oct-17-2016, 12:52 PM by hugobaur.)
Hi Guys,
Thanks to answers, i'm using Windows OS.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Autor: Hugo Baur [email protected]
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os.path
import shutil
from datetime import date
now = date.today()
#FILENAME = "E:/ENEL/Modelos/DC201609/DC201609-sem1/DADGER.rv0"
WORD = "& NO. SEMANAS NO MES INIC. DO ESTUDO=> 5"
#-------------------------FUNÇÕES--------------------------------
def criarPastaDestino(): # FUNÇÃO PARA CRIAR A PASTA RECIPIENTE , CRIAR AS SUB PASTAS E COPIAR SEU CONTEUDO
os.mkdir(directoryPath)
for x in range(0, int(meses)):
if x <= 9:
aux = (directoryPath + "DC" + str(now.year) + "0" + str(int(iniMes) + x) + "/")
# os.mkdir(aux)
numeroSemanas = find_word_in_file(origem + "/DADGER.rv0", WORD)
teste = numeroSemanas.replace('& NO. SEMANAS NO MES INIC. DO ESTUDO=> ', '')
if x < 1:
os.mkdir(aux)
for i in range(1, int(teste)-2):
a =str(x)
b = str(i)
#os.mkdir (aux + "DC" + str(now.year) + str(int(iniMes)) + "-sem" + b)
#os.mkdir (aux + "Relatorio_Sumario-" + "DC" + str(now.year) + str(int(iniMes))+ "-sem" + b)
if x <= 9:
criarpastas = (aux + "DC" + str(now.year) + "0" + str(int(iniMes) + x) + "-sem" + b)
criarpastasrelatorio = (aux + "Relatorio_Sumario-" + "DC" + str(now.year) + "0" + str(int(iniMes) + x) + "-sem" + b)
else:
criarpastas = (aux + "DC" + str(now.year) + str(int(iniMes) + x) + "-sem" + b)
criarpastasrelatorio = (aux + "Relatorio_Sumario-" + "DC" + str(now.year) + str(int(iniMes) + x) + "-sem" + b)
shutil.copytree(origem, criarpastas + "/")
shutil.copytree(origem, criarpastasrelatorio + "/")
# ALTERAR EXTENSÃO DE ARQUIVOS
os.rename(criarpastas + "/"+ "DADGNL.RV0", criarpastas + "/"+ "DADGNL.RV" + str(i-1))
os.rename(criarpastas + "/"+ "DADGER.RV0", criarpastas + "/"+ "DADGER.RV" + str(i-1))
os.rename(criarpastas + "/"+ "PREVS.RV0", criarpastas + "/"+ "PREVS.RV" + str(i-1))
os.rename(criarpastas + "/"+ "RV0.dat", criarpastas + "/"+ "RV" + str(i-1) +".dat")
os.rename(criarpastas + "/"+ "VAZOES.RV0", criarpastas + "/"+ "VAZOES.RV" + str(i-1))
os.rename(criarpastasrelatorio + "/"+"DADGNL.RV0", criarpastasrelatorio + "/"+ "DADGNL.RV" + str(i-1))
os.rename(criarpastasrelatorio + "/"+"DADGER.RV0", criarpastasrelatorio + "/"+ "DADGER.RV" + str(i-1))
os.rename(criarpastasrelatorio + "/"+"PREVS.RV0", criarpastasrelatorio + "/"+ "PREVS.RV" + str(i-1))
os.rename(criarpastasrelatorio + "/"+"RV0.dat", criarpastasrelatorio + "/"+ "RV" + str(i-1) +".dat")
os.rename(criarpastasrelatorio + "/"+ "VAZOES.RV0", criarpastasrelatorio + "/"+ "VAZOES.RV" + str(i-1))
# E:/ENEL/Modelos/DC201609/DC201609-sem1
# C:/TESTESISTEMA
# E:/ENEL/Modelos/NW201610
else:
if (int(iniMes) + x) <= 9: #8 9 12
aux = (directoryPath + "DC" + str(now.year) + "0" + str(int(iniMes) + x) + "/")
else:
if (int(iniMes) + x) > 9 and x < 12:
aux = (directoryPath + "DC" + str(now.year) + str(int(iniMes) + x) + "/")
else:
if (int(iniMes) + x) >= 12 and x < 21:
aux = (directoryPath + "DC" + str(now.year + 1) + "0" + str(int(iniMes) + x - 12) + "/")
else:
if (int(iniMes) + x) >= 21 and x < 24:
aux = (directoryPath + "DC" + str(now.year + 1) + str(int(iniMes) + x - 12) + "/")
else:
if (int(iniMes) + x) >= 24 and x < 33:
aux = (directoryPath + "DC" + str(now.year + 2) + "0" + str(int(iniMes) + x - 24) + "/")
else:
if (int(iniMes) + x) >= 33 and x < 36:
aux = (directoryPath + "DC" + str(now.year + 2) + str(int(iniMes) + x - 24) + "/")
else:
if (int(iniMes) + x) >= 36 and x < 45:
aux = (directoryPath + "DC" + str(now.year + 3) + "0" + str(int(iniMes) + x - 36) + "/")
else:
if (int(iniMes) + x) >= 45 and x < 48:
aux = (directoryPath + "DC" + str(now.year + 3) + str(int(iniMes) + x - 36) + "/")
else:
if (int(iniMes) + x) >= 48 and x < 57: #44 45 48
aux = (directoryPath + "DC" + str(now.year + 4) + "0" + str(int(iniMes) + x - 48) + "/")
else:
if (int(iniMes) + x) >= 57 and x < 60: #56 57 60
aux = (directoryPath + "DC" + str(now.year + 4) + str(int(iniMes) + x - 48) + "/")
shutil.copytree(origem, aux + "/")
# FUNÇÃO LOCALIZA A STRING "& NO. SEMANAS NO MES INIC. DO ESTUDO=> 5" E RETORNA O NUEMRO DE SEMANAS
def find_word_in_file(FILENAME, WORD):
f = open(FILENAME, "r")
file_array = f.readlines()
f.close()
for i in file_array:
if i.find(WORD) >= 0:
print("Localizado a string: " + i)
return i
return False
def newave_creator():
if int(now.month) <= 9:
path = (destino + "/" + "NW" + str(now.year) + "0" + str(int(now.month)) + "/")
else:
path = (destino + "/" + "NW" + str(now.year) + str(int(now.month)) + "/")
shutil.copytree(origemNewave, path)
print ("\n\n### Arquivos NEWAVE criados com sucesso! ###\n")
#-------------------------MENU-----------------------------------
digito = True
while digito:
print("""
1.Gerar dados para o modelo DCOMP
2.Gerar dados para o modelo NEWAVE
3.Opção 3
4.Exit/Quit
""")
digito = input("O que gostaria de fazer? ")
if digito == "1":
print("\nModelo DECOMP")
origem = input("Digite o caminho da ORIGEM dos dados: ") # DEFINE O PATH ORIGEM
nomedapasta = input("Digite o nome da pasta que será criada: ") # DEFINE O NOME DA PASTA A SER CRIADA
destino = input("Digite o caminho DESTINO dos dados: ") # DEFINE O PATH DE DESTINO
meses = input("Digite o numero de meses: ") # RECEBE O NUMERO DE MESES DE ESTUDO
iniMes = input("Digite o mês de início: ") # RECEBE O INICIO DE MESES DE ESTUDO
directoryPath = (destino + "/" + nomedapasta + "/") # PEGAR O DESTINO E CONCATENAR COM O NOME ESCOLHIDO DA PASTA PELO USUÁRIO
print("\n Você inseriu o caminho ORIGEM: " + origem + " e caminho DESTINO: " + directoryPath) # INFORMA AO USUÁRIO O PATH ORIGEM E O DESTINO
criarPastaDestino()
print("\n\n ## CRIAÇÃO BEM SUCEDIDA ##\n")
print("__________________________________________________________________")
elif digito == "2":
print("\nModelo NEWAVE")
origemNewave = input("Digite o caminho da ORIGEM dos dados: ") # DEFINE O PATH ORIGEM
destino = input("Digite o caminho DESTINO dos dados: ") # DEFINE O PATH DE DESTINO
newave_creator()
print ("__________________________________________________________________")
elif digito == "3":
path = input("Digite o caminho da ORIGEM dos dados: ") # DEFINE O PATH ORIGEM
numeroSemanas = find_word_in_file(path + "/DADGER.rv0", WORD)
teste = numeroSemanas.replace('& NO. SEMANAS NO MES INIC. DO ESTUDO=> ', '')
print("Número de semanas lido: " + teste + "O número de semanas que será criado: " + str(int(teste) - 2))
elif digito == "4":
print("\n### OBRIGADO, TENHA UM BOM DIA! ###")
digito = None
else:
print("\n#### Digito inválido, por favor digite um dos números do menu. ###")
So, to replices that, you need archives .txt, just 2.
one with the name "DADGER.rv0" containing the string "& NO. SEMANAS NO MES INIC. DO ESTUDO=> 5" and another with any name and any content, only for viewing.
First - Put de path od the first archive
Second - Name of the new archive
third - Path where the new files will be created
fourth - Number of the months
fifth - Number of the initial month
If you start using a initial month, its ok. Works!
if you start with the month 10 for example, doesn't work.
Posts: 3,458
Threads: 101
Joined: Sep 2016
I have no desire to read through all that, but it looks like you've got two values, year and month, and you're incrementing the month. You could check to see if the new value is over 12 and reset it to 1... >>> dates = []
>>> year = 2016
>>> month = 1
>>> for i in range(20):
... dates.append('{0:04d}{1:02d}'.format(year, month))
... month += 1
... if month > 12:
... month = 1
... year += 1
...
>>> dates
['201601', '201602', '201603', '201604', '201605', '201606', '201607', '201608', '201609', '201610', '201611', '201612', '201701', '201702', '201703', '201704', '201705', '201706', '201707', '201708']
>>> Then there's also the datetime module and friends in case you don't want to do that math yourself.
Posts: 2,168
Threads: 35
Joined: Sep 2016
This is what I came up with.
from datetime import date
def yield_file_dates(start_year, start_month, amount_of_months):
current_date = date(start_year, start_month, 1)
for _ in range(amount_of_months):
yield 'DC{:%Y%m}'.format(current_date)
if current_date.month == 12:
current_date = current_date.replace(current_date.year + 1, 1)
else:
current_date = current_date.replace(month=current_date.month + 1)
for file_date in yield_file_dates(2016, 10, 5):
print(file_date) Output: DC201610
DC201611
DC201612
DC201701
DC201702
Posts: 7
Threads: 2
Joined: Oct 2016
Yes!!!! WORKS!
Thanks to help me
I really appreciate that!
|