كود #Python لتحويل ملف #CSV الى ملف #EXCEL مع شاشة الخرج.
للمزيد: @CodeProgrammer
قم بدعوة اصدقاءك من اجل المزيد والاستمرار.
للمزيد: @CodeProgrammer
قم بدعوة اصدقاءك من اجل المزيد والاستمرار.
Title: Convert from Excel file to CSV file using #Python
كود #بايثون لتحويل ملف #Excel الى ملف #CSV باستخدام مكتبة #xlrd مرفقا بالشرح الوافي ضمن الكود بالاضافة لنتيجة التنفيذ وال #Source_Code الخاص بهذا الكود.
للمزيد قم بمشاركة المنشور ودعوة اصدقاءك للاستفادة: @CodeProgrammer
كود #بايثون لتحويل ملف #Excel الى ملف #CSV باستخدام مكتبة #xlrd مرفقا بالشرح الوافي ضمن الكود بالاضافة لنتيجة التنفيذ وال #Source_Code الخاص بهذا الكود.
للمزيد قم بمشاركة المنشور ودعوة اصدقاءك للاستفادة: @CodeProgrammer
Media is too big
VIEW IN TELEGRAM
Loading CSV files into a database using Python.
#python #csv #dataAnalysis
⭐️ BEST DATA SCIENCE CHANNELS ON TELEGRAM ⭐️
#python #csv #dataAnalysis
Please open Telegram to view this post
VIEW IN TELEGRAM
👍14❤4💯2
In Python, handling CSV files is straightforward using the built-in
#python #csv #pandas #datahandling #fileio #interviewtips
👉 @DataScience4
csv module for reading and writing tabular data, or pandas for advanced analysis—essential for data processing tasks like importing/exporting datasets in interviews.# Reading CSV with csv module (basic)
import csv
with open('data.csv', 'r') as file:
reader = csv.reader(file)
data = list(reader) # data = [['Name', 'Age'], ['Alice', '30'], ['Bob', '25']]
# Writing CSV with csv module
import csv
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age']) # Header
writer.writerows([['Alice', 30], ['Bob', 25]]) # Data rows
# Advanced: Reading with pandas (handles headers, missing values)
import pandas as pd
df = pd.read_csv('data.csv') # df = DataFrame with columns 'Name', 'Age'
print(df.head()) # Output: First 5 rows preview
# Writing with pandas
df.to_csv('output.csv', index=False) # Saves without row indices
#python #csv #pandas #datahandling #fileio #interviewtips
👉 @DataScience4
❤4👍4
#TelegramBot #Python #SQLite #DataExport #CSV #API
Lesson: Creating a Telegram Bot to Export Channel Members to a CSV File
This tutorial guides you through building a Telegram bot from scratch. When added as an administrator to a channel, the bot will respond to an
IMPORTANT NOTE: Due to Telegram's privacy policy, bots CANNOT access users' phone numbers. This field will be marked as "N/A".
---
First, create a bot via the @BotFather on Telegram. Send it the
Next, set up your Python environment. Install the necessary library:
Create a new Python file named
---
To fulfill the requirement of using a database, we will log every export request. Create a new file named
---
Now, we'll write the core function in
Lesson: Creating a Telegram Bot to Export Channel Members to a CSV File
This tutorial guides you through building a Telegram bot from scratch. When added as an administrator to a channel, the bot will respond to an
/export command from the channel owner, exporting the list of members (Username, User ID, etc.) to a CSV file and storing a log of the action in a SQLite database.IMPORTANT NOTE: Due to Telegram's privacy policy, bots CANNOT access users' phone numbers. This field will be marked as "N/A".
---
#Step 1: Bot Creation and Project SetupFirst, create a bot via the @BotFather on Telegram. Send it the
/newbot command, follow the instructions, and save the HTTP API token it gives you.Next, set up your Python environment. Install the necessary library:
python-telegram-bot.pip install python-telegram-bot
Create a new Python file named
bot.py and add the basic structure. Replace 'YOUR_TELEGRAM_API_TOKEN' with the token you got from BotFather.import logging
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes
# Enable logging
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO)
TOKEN = 'YOUR_TELEGRAM_API_TOKEN'
def main() -> None:
"""Start the bot."""
application = Application.builder().token(TOKEN).build()
# We will add command handlers here in the next steps
# application.add_handler(CommandHandler("export", export_members))
print("Bot is running...")
application.run_polling()
if __name__ == "__main__":
main()
# Hashtags: #Setup #TelegramAPI #PythonBot #BotFather
---
#Step 2: Database Setup for Logging (database.py)To fulfill the requirement of using a database, we will log every export request. Create a new file named
database.py. This separates our data logic from the bot logic.import sqlite3
from datetime import datetime
DB_NAME = 'bot_logs.db'
def setup_database():
"""Creates the database table if it doesn't exist."""
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS export_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
chat_id INTEGER NOT NULL,
chat_title TEXT,
requested_by_id INTEGER NOT NULL,
requested_by_username TEXT,
timestamp TEXT NOT NULL
)
''')
conn.commit()
conn.close()
def log_export_action(chat_id, chat_title, user_id, username):
"""Logs a successful export action to the database."""
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cursor.execute(
"INSERT INTO export_logs (chat_id, chat_title, requested_by_id, requested_by_username, timestamp) VALUES (?, ?, ?, ?, ?)",
(chat_id, chat_title, user_id, username, timestamp)
)
conn.commit()
conn.close()
# Hashtags: #SQLite #DatabaseDesign #Logging #DataPersistence
---
#Step 3: Implementing the Export Command and Permission CheckNow, we'll write the core function in
bot.py. This function will handle the /export command. The most crucial part is to check if the user who sent the command is the creator of the channel. This prevents any admin from exporting the data.❤2
# This code continues inside the export_members function from Step 3
# --- Data Fetching and CSV Generation ---
try:
# Using get_chat_administrators is a reliable way for bots to get a list of some members.
# Getting all subscribers can be limited by the API for standard bots.
members_to_export = await context.bot.get_chat_administrators(chat.id)
# Create a CSV in-memory
output = io.StringIO()
writer = csv.writer(output)
# Write header row
header = ['User ID', 'First Name', 'Last Name', 'Username', 'Phone Number']
writer.writerow(header)
# Write member data
for admin in members_to_export:
member = admin.user
row = [
member.id,
member.first_name,
member.last_name or 'N/A',
f"@{member.username}" if member.username else 'N/A',
'N/A (Privacy Protected)' # Bots cannot access phone numbers
]
writer.writerow(row)
# Prepare the file for sending
output.seek(0)
file_to_send = io.BytesIO(output.getvalue().encode('utf-8'))
file_to_send.name = f"{chat.title or 'channel'}_members.csv"
await context.bot.send_document(chat_id=user.id, document=file_to_send,
caption="Here is the list of exported channel members.")
# Log the successful action
db.log_export_action(chat.id, chat.title, user.id, user.username)
except Exception as e:
logging.error(f"Failed to export members for chat {chat.id}: {e}")
await update.message.reply_text(f"An error occurred during export: {e}")
# Hashtags: #CSV #DataHandling #InMemoryFile #PythonCode
Make sure to add the handler line in
main() as mentioned in Step 3 to activate the command.---
#Step 5: Final Results and DiscussionTo use the bot:
• Run the
bot.py script.• Add your bot as an administrator to your Telegram channel.
• As the creator of the channel, send the
/export command in the channel.• The bot will respond that it's processing the request.
• You will receive a private message from the bot containing the
members.csv file.• A log entry will be created in the
bot_logs.db file in your project directory.Discussion of Results and Limitations:
Privacy is Paramount: The most significant result is observing Telegram's privacy protection in action. Bots cannot and should not access sensitive user data like phone numbers. This is a crucial security feature of the platform.
Permission Model: The check for
admin.status == 'creator' is robust and ensures that only the channel owner can trigger this sensitive data export, aligning with good security practices.API Limitations: A standard bot created with BotFather has limitations. While it can always get a list of administrators, fetching thousands of regular subscribers can be slow, rate-limited, or incomplete. For massive-scale scraping, developers often turn to "userbots" (using a regular user's API credentials), which have different rules and are against Telegram's Terms of Service if used for spam or abuse.
Database Logging: The use of SQLite provides a simple yet effective audit trail. You can see which channels were exported, by whom, and when. This is essential for accountability.
This project demonstrates a practical use for a Telegram bot while also highlighting the importance of working within the security and privacy constraints of an API.
#ProjectComplete #EthicalAI #DataPrivacy #TelegramDev
━━━━━━━━━━━━━━━
By: @CodeProgrammer ✨
❤2