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")