Writing to a File
To write content to a file, you can use the
The write() method writes a string to the file.
Example:
The
Example:
To write content to a file, you can use the
write() or writelines() methods. Opening a file in write ('w') mode will create the file if it doesn’t exist or overwrite it if it does.write() MethodThe write() method writes a string to the file.
Example:
with open("output.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is a Python program.\n")writelines() MethodThe
writelines() method takes a list of strings and writes them to the file.Example:
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("output.txt", "w") as file:
file.writelines(lines)
👍1
Appending to a File
When you want to add content to the end of an existing file without overwriting it, you can use the append mode ('
Example:
When you want to add content to the end of an existing file without overwriting it, you can use the append mode ('
a').Example:
with open("output.txt", "a") as file:
file.write("This line will be appended.\n")Working with Binary Files
In addition to text files, you can also work with binary files such as images, videos, and executables by opening the file in binary mode ('
Reading a Binary File
Example:
Writing to a Binary File
Example:
In addition to text files, you can also work with binary files such as images, videos, and executables by opening the file in binary mode ('
b').Reading a Binary File
Example:
with open("image.jpg", "rb") as file:
binary_content = file.read()
print(binary_content) # Outputs the binary content of the imageWriting to a Binary File
Example:
with open("new_image.jpg", "wb") as file:
file.write(binary_content) # Writes binary content to a new fileHandling File Exceptions
File operations can result in errors, such as trying to open a non-existent file in read mode. You can handle such cases using exception handling with
Example:
File operations can result in errors, such as trying to open a non-existent file in read mode. You can handle such cases using exception handling with
try and except.Example:
try:
with open("non_existent_file.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found. Please check the filename.")
👍1
File Positioning:
Example:
seek() and tell()tell(): Returns the current position of the file pointer (in bytes).seek(offset, from_what): Moves the file pointer to a specified location.Example:
with open("example.txt", "r") as file:
print(file.tell()) # Prints the current position of the file pointer
file.seek(0) # Moves the pointer to the beginning of the file
print(file.read())Practice Exercises
Exercise 1: Word Count
Exercise 2: File Copying
Exercise 3: Reverse Content
Exercise 4: Binary File Handling
Exercise 5: Character Frequency
Exercise 1: Word Count
Write a Python program to count the number of words in a text file.
Exercise 2: File Copying
Write a Python program that copies the contents of one file into another file.
Exercise 3: Reverse Content
Write a Python program that reads the content of a file and writes it to a new file in reverse order
Exercise 4: Binary File Handling
Write a Python program that opens a binary file (such as an image) and creates a copy of it.
Exercise 5: Character Frequency
Write a Python program that reads a text file and counts the frequency of each character in the file.
❤2👍2
Python Codes Basic to Advance
Practice Exercises Exercise 1: Word Count Write a Python program to count the number of words in a text file. Exercise 2: File Copying Write a Python program that copies the contents of one file into another file. Exercise 3: Reverse Content Write a Python…
Send solution in comment section
Urgent need of python Developer
Skill required:
Python in advance
Database: Mongodb
And Pyrogram Library
Dm:- @Itz_legendCoder
Skill required:
Python in advance
Database: Mongodb
And Pyrogram Library
Dm:- @Itz_legendCoder
couple_finder.py
1.1 KB
THIS PROGRAM WILL FIND YOUR COUPLE YOU JUST NEED TO CHOOSE YOUR GENDER AND ENTER NAME
try:
from faker import Faker
except:
import os
os.system("pip install faker")
fake = Faker()
F = fake.first_name_female()
M = fake.first_name_male()
enter = input('''Select your Gender!
M:---> for Male
F:---> for Female \t''').upper()
if "M" in enter:
PRINCE = "Enter your name I will find your princess 💖\t"
M = input(PRINCE).capitalize()
elif "F" in enter:
PRINCESS = "Enter your name I will find your Prince💖\t"
F = input(PRINCESS).capitalize()
elif input.str("M", "F") not in enter:
print("try again")
else:
print("wrong input")
# Made by @mr_sukkun
couple1 = {M: F}
couple = {value: key for key, value in couple1.items()}
if "M" in enter and M in couple1:
print("Hey "+ M, couple1[M], "is your Girlfriend 💖")
if "F" in enter and F in couple:
print("Hey "+F, couple[F], "is your Boyfriend 💖")
👍5❤2
Forwarded from Cᴏᴅᴇs Sɴɪᴘᴘᴇᴛs (</> ᴍᴜᴋᴇsʜ </>)
What is the output of this code snippet?
Anonymous Quiz
45%
(1, 2, 3, 4, 5)
30%
[1, 2, 3, 4, 5]
21%
Error
3%
None
Convert PDF to docx using Python
📂 Tags: #DataScience #Python #ML #AI #LLM #BIGDATA #Courses
⭐️Add coding folder 👇
https://t.me/addlist/2UhsQW_cGzkxMzg1
📂 Tags: #DataScience #Python #ML #AI #LLM #BIGDATA #Courses
⭐️Add coding folder 👇
https://t.me/addlist/2UhsQW_cGzkxMzg1
👍4🔥1
Exclusion from the queue
The collections.deque() class is a generalization of stacks and queues, and represents a deque. A deque() supports thread-safe, memory-efficient operations for inserting and removing elements of a sequence from either side, with roughly the same O(1) performance in either direction.
#CodeSnippet
#ProgrammingFun
#python3
#python
⭐️Add coding folder 👇
https://t.me/addlist/2UhsQW_cGzkxMzg1
The collections.deque() class is a generalization of stacks and queues, and represents a deque. A deque() supports thread-safe, memory-efficient operations for inserting and removing elements of a sequence from either side, with roughly the same O(1) performance in either direction.
#CodeSnippet
#ProgrammingFun
#python3
#python
⭐️Add coding folder 👇
https://t.me/addlist/2UhsQW_cGzkxMzg1
❤1👍1
Forwarded from PYTHON PROGRAMMING (</> ᴍᴜᴋᴇsʜ </>)
Creating Virtual Environment for Python
» Download Python
» Steps to create '
1. Navigate to the folder where you want to make your project
Example:
2. Open terminal (local terminal, command prompt, or vs code terminal) in that folder
3. Now, use these commands
4. Your virtual environment is created in that folder, now activate this virtual environment using this command.
Command for 'Command Prompt':
Command for 'Powershell':
Command for Git Bash or WSL:
If Powershell gives you error like
5. Congratulations🎊 Your virtual environment activated now make your project
Happy Coding 👨💻
» Download Python
First you need python installed in your local machine to create virtual environment.
Download Python from Here
» Steps to create '
.env' folder (virtual environment for python)1. Navigate to the folder where you want to make your project
Example:
cd D:/code/
2. Open terminal (local terminal, command prompt, or vs code terminal) in that folder
3. Now, use these commands
python --version # Type this and hit enter to verify the python version
# Now use these commands
python -m venv .env
4. Your virtual environment is created in that folder, now activate this virtual environment using this command.
Command for 'Command Prompt':
.\env\Scripts\activate
Command for 'Powershell':
.\env\Scripts\Activate.ps1
Command for Git Bash or WSL:
source \.env\bin\activate
If Powershell gives you error like
File cannot be loaded because running scripts is disabled then use this command!Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
5. Congratulations🎊 Your virtual environment activated now make your project
Happy Coding 👨💻
👍4❤1
def func(a, b=2, c=3):
return a + b + c
print(func(1, c=4))
👍1
Forwarded from Cᴏᴅᴇs Sɴɪᴘᴘᴇᴛs (</> ᴍᴜᴋᴇsʜ </>)
· Send paid media using pyrofork
· Requirements
· Requirements
pip install pyrofork
from pyrogram import Client,idle,filters,types
app=Client("paidmedia",bot_token="bot_token_here",api_hash="api_hash_here",api_id="api_id_here")
@app.on_message(filters.command("sendpaidmedia"))
async def payout(b,m) :
await b.send_paid_media(
chat_id=m.chat.id,
stars_amount=100,
media=[
types.InputMediaPhoto("img.jpg"),
],
caption="This is a secret message. pay to watch")
if __name__=="__main__":
print("client started")
app.run()
idle()
@CodesSnippet
Happy Coding 👨💻
❤1
🎉📚 Exciting Offer Alert! 🎉📚
get ₹1000 off on your admission or re-registration in IGNOU
🌟 Don't miss out on this fantastic opportunity! 🌟
Note :
Get 100% ✅ gurrenty if any issue your money will be refunded💯 within 10 minutes
Hurry, limited time offer! ⏳
👉 Contact us now to grab your discount:- @itz_legendcoder 📞💬
get ₹1000 off on your admission or re-registration in IGNOU
🌟 Don't miss out on this fantastic opportunity! 🌟
Note :
Get 100% ✅ gurrenty if any issue your money will be refunded💯 within 10 minutes
Hurry, limited time offer! ⏳
👉 Contact us now to grab your discount:- @itz_legendcoder 📞💬
🎉 Happy New Year, Coders! 🎉
As we step into this new year, may your code be bug-free and your projects be fulfilling! 💻✨
🔧 Embrace challenges as opportunities to learn and grow! Remember, every line of code is a step toward mastery. 🚀
🌟 Keep pushing boundaries, exploring new technologies, and collaborating with others. Your creativity knows no limits! 🌐
Let’s make this year the one where your ideas come to life. Happy coding and happy New Year! 🍾🥳💻
As we step into this new year, may your code be bug-free and your projects be fulfilling! 💻✨
🔧 Embrace challenges as opportunities to learn and grow! Remember, every line of code is a step toward mastery. 🚀
🌟 Keep pushing boundaries, exploring new technologies, and collaborating with others. Your creativity knows no limits! 🌐
Let’s make this year the one where your ideas come to life. Happy coding and happy New Year! 🍾🥳💻
❤1
Get System Information
Jᴏɪɴ ᴜs :- @Python_Codes_Pro
Support group :- @python_group_pro
import psutil
import platform
from sys import version as pyver
from pyrogram import __version__ as pyrover
def get_system_info():
p_core = psutil.cpu_count(logical=False) # Physical cores
t_core = psutil.cpu_count(logical=True) # Logical cores
ram = str(round(psutil.virtual_memory().total / (1024.0**3))) + " GB"
try:
cpu_freq = psutil.cpu_freq().current
if cpu_freq >= 1000:
cpu_freq = f"{round(cpu_freq / 1000, 2)} ɢʜᴢ"
else:
cpu_freq = f"{round(cpu_freq, 2)} ᴍʜᴢ"
except Exception:
cpu_freq = "ғᴀɪʟᴇᴅ ᴛᴏ ғᴇᴛᴄʜ"
# HDD information
hdd = psutil.disk_usage("/")
total_hdd = round(hdd.total / (1024.0**3), 2) # Total space in GB
used_hdd = round(hdd.used / (1024.0**3), 2) # Used space in GB
free_hdd = round(hdd.free / (1024.0**3), 2) # Free space in GB
# Return system information as a dictionary
return {
"Physical Cores": p_core,
"Logical Cores": t_core,
"RAM": ram,
"CPU Frequency": cpu_freq,
"HDD Total": f"{total_hdd} GB",
"HDD Used": f"{used_hdd} GB",
"HDD Free": f"{free_hdd} GB",
"Python Version": pyver.split()[0] if pyver else "Unknown",
"Pyrogram Version": pyrover
}
if __name__ == "__main__":
system_info = get_system_info()
text=""
for key, value in system_info.items():
text+=f"{key}: {value}\n"
print(text)
Jᴏɪɴ ᴜs :- @Python_Codes_Pro
Support group :- @python_group_pro
❤1