Hello. I am writing a bot for Telegram , but not how I can not deal with one question: how to make the bot write user and user id in a separate file. How can this be realized?

Thank you in advance.

  • one
    the question should be reformulated, since its essence is “how to write something to a file in python” and telegrams along with bots have nothing to do with it - Anatol

2 answers 2

Like this:

 # Отправляем имя пользователя и его id def FileUserID(user, id): # Открываем файл для записи file = open(str(id)+'.txt', 'w') # Записываем file.write("User: %s, id: %i\n" %(user, id)) # Закрываем файл file.close() 

You can send for the place w other parameters:

  • r - open for reading (is the default).

  • w open for writing, the contents of the file is deleted, if the file does not exist, a new one is created.

  • x - open for writing if the file does not exist, otherwise an exception.
  • a - opening for additional recording, information is added to the end of the file.
  • b - opening in binary mode.
  • t - open in text mode (is the default).
  • + - opening for reading and writing

But for such purposes it is better to use a database, for example: PostgreSQL , MySQL or SQLite - I would advise you to use SQLite its advantages:

  • The entire database is stored in 1 file.
  • Does not require a separate server where the base would spin

minuses:

  • I think this is clear from the pros, it is much slower than other relational databases, but this is not particularly critical with a small amount given

SQLite example :

 import sqlite3 # Отправляем id пользователя и имя def AddUser(user_id, user_name): # Подключаемся к SQLite conn = sqlite3.connect('user.db') c = conn.cursor() # Обработка SQL исключений try: # Выполняем SQL запрос c.execute("INSERT INTO users (user_id, user_name) VALUES (?, ?);", (user_id, user_name)) except sqlite3.DatabaseError as error: # В случаи ошибки print("Error:", error) # Завершаем транзикцию conn.commit() # Закрываем соединение conn.close() # Добавляем пользователя Test c id 1 AddUser(1, "Test") 

Table model for SQLite:

 CREATE TABLE "users" ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, user_id INT NOT NULL, user_name TEXT ); -- Добавил ключ на уникальность для поля user_id CREATE UNIQUE INDEX table_name_user_id_uindex ON "users" (user_id); -- Добавил ключ для поля user_id CREATE INDEX table_name_user_name_index ON "users"(user_name); 

But if you want to write to a file, it is best to use a separate file for each user.

I would suggest the following structure:

 user/ <-- Каталог с файлами id1.json <-- Файл пользователя 1 (1 - это id пользователя) id2.json id3.json id4.json 

The id1.json file stores user information in json format:

  { "id":"1", "user":"user1" } 

Well, to modify the code a bit:

 import json # Отправляем имя пользователя и его id def AddUser(id, user): # Открываем файл для записи file = open('id'+str(id)+'.json', 'w') # Создаем json строку json_str = json.dumps({'user': user, 'id': id}) # Записываем наш json file.write(json_str) # Закрываем файл file.close() # Добавляем пользователя Test c id 1 AddUser(1, "Test") 

And as an option for .ini (wrote anyway):

 import configparser def AddUser(id, user): config = configparser.RawConfigParser() config['USERS'] = {'user': user, 'id': id} config.write(open('user/id'+str(id)+'.ini', 'w')) AddUser(1, "Test") 
  • You have a lot of stylistic errors in the code. If you want to improve the code (if you are sure that it works) and are ready to hear any comments about the code, then ask a question with a label inspection code. Read the description of the label to find out how such questions differ from ordinary Stack Overflow questions. - jfs
  • @jfs is generally code for testing in Python v3 (and it even works), but you are right, the code writing style is different and there are problems in the answer, but I tried to give the most detailed answer possible. - users
  • Performance is a requirement for questions with a label [inspection code]. Here are a couple of examples . - jfs
  • @jfs the only thing I do not understand a little what is it all about? In terms of Matvey Polovskiy, he doesn’t react to the answer, and he will no longer go to the hands of a stack. Yes, all 4 examples from the answer workers xD - users
  • comments on the code for you. Simple things that can make your future code more idiomatic. - jfs
 import json def file_user_id(user, id): with open("{}.txt".format(id), "w") as file: file.write(json.dumps(dict(user=user, id=id))) 
  • please give more detailed answers - cache