Answer the question
In order to leave comments, you need to log in
How to count in python from a txt file the lines with the date of the last 7 days?
Please help with solving the problem. I'm trying to make telegram bot statistics, I implemented the user counter by adding the following code to the start command (entering user_id into a text file):
file = open('stat.txt', 'r+')
database_id = file.read()
if str(message .from_user.id) in database_id:
file.close()
else:
file.write(datetime.datetime.today().strftime("%d-%m-%Y") + " " + str(message.from_user. id) + "\n")
file.close()
added to the statistics command for reading:
def stat(message):
with open('stat.txt', 'r') as file:
count_users = len(file.readlines( ))
that is, we count the number of lines, these are the users of the bot. But now I want to make the number of new users for the last 7 days, I just can’t figure out how to implement it, I want to make it so that the number of lines with the date for the last 7 days is displayed from the file. txt file example:
Answer the question
In order to leave comments, you need to log in
Why use text files?
It may be more practical to work with the database, everything is easy and simple there, you don’t have to suffer a lot
Meditate
https://russianblogs.com/article/7951910016/
After meditation, compose an awk command, get its output in python and then proceed
If you want to conveniently work with statistics, but it is stored in txt, then use Pandas, for example, convert the file to a table and work like with a spreadsheet, uploading everything you need).
But if you really want a primitive way, something like this.
You make a function, pass a date as an argument or a number of days,
start a counter variable
, open a file, read line by line .readlines ()
from a line, cut characters through slices according to the number of characters in the date, convert them to date data type
if the date is in the range you need, then counter +1
, close the file,
return the value from the counter)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question