Introduction
Do you often struggle with tasks like batch renaming photos in a folder but don't know where to start? Or do you need to handle a lot of date and time data and get overwhelmed by various format conversions? These seemingly complex operations can be easily handled with Python.
As a Python developer, I deeply understand the importance of system programming and file handling. Today, let's explore those powerful and practical built-in modules in Python and see how to elegantly handle these common needs.
File Mastery
When it comes to system programming, the os
module is indispensable. It's like the "diplomat" between Python and the operating system, handling various file and directory operations.
Did you know? Creating, deleting, and renaming files in Python is as simple as playing with building blocks. Let's look at an example:
import os
os.mkdir('my_photos')
files = os.listdir('.')
for i, file in enumerate(files):
if file.endswith('.jpg'):
new_name = f'photo_{i+1}.jpg'
os.rename(file, new_name)
This code can help you easily achieve batch renaming of photos. Personally, I particularly like using os.path.join()
to construct paths, as it automatically handles path separators for different operating systems, allowing the code to run perfectly on both Windows and Linux.
Time Management
Handling time is a topic every programmer cannot avoid. Python's datetime
module is specifically designed for this purpose.
from datetime import datetime, timedelta
now = datetime.now()
next_week = now + timedelta(days=7)
print(f"Current time is: {now.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"Same time next week is: {next_week.strftime('%Y-%m-%d %H:%M:%S')}")
Here's an interesting application scenario: I once made a small tool for automatically generating weekly work reports, using datetime
to calculate the start and end times of each week and then automatically organizing the work content for that period. This module, when used well, can make time handling particularly elegant.
Data Interconversion
In actual development, handling JSON data can be said to be commonplace. The json
module is a powerful assistant specifically designed to meet such needs.
import json
user_info = {
'name': 'Xiao Ming',
'age': 25,
'skills': ['Python', 'JavaScript']
}
json_str = json.dumps(user_info, ensure_ascii=False)
print(f"JSON string: {json_str}")
parsed_data = json.loads(json_str)
print(f"Parsed data: {parsed_data}")
I often use this module to handle data returned by APIs. Here's a tip to share: add the ensure_ascii=False
parameter in dumps()
, so the output JSON string can correctly display Chinese characters.
Random Walk
The random
module is one of my favorites. It can not only generate random numbers but also implement many interesting functions.
import random
lucky_number = random.randint(1, 100)
fruits = ['Apple', 'Banana', 'Orange', 'Grape']
today_fruit = random.choice(fruits)
random.shuffle(fruits)
This module is particularly useful in scenarios like game development, data sampling, and test case generation. I once made a simple lottery system using random.choices()
with different prize weights.
Regex Magic
Regular expressions are a sharp tool for text processing, and the re
module is the standard in Python for handling regular expressions.
import re
text = "Xiao Ming's phone number is 13912345678, Xiao Hong's number is 13887654321"
phone_numbers = re.findall(r'1[3-9]\d{9}', text)
print(f"Extracted phone numbers: {phone_numbers}")
content = "This is a sensitive word, and that is also a sensitive word"
clean_content = re.sub('sensitive word', '***', content)
Regular expressions may seem a bit complex, but mastering them is like having a Swiss Army knife, making text data processing particularly efficient. I suggest starting with simple patterns and gradually increasing the difficulty.
Conclusion
Python's system programming modules provide us with powerful tools, but the key is knowing what tool to use in what scenario. As I often say, programming is not about memorizing APIs but understanding the characteristics and applicable scenarios of each tool.
Have you encountered any interesting issues while handling files and system interactions? Or do you have any unique insights into using a particular module? Feel free to share your experiences and thoughts in the comments.
Learning programming is like exploring a new continent; mastering a new skill opens up new possibilities. Let's continue sailing in the sea of Python and discover more exciting knowledge.
Which of these system programming modules do you use most often? What usage tips would you like to share with everyone?