当前位置:实例文章 » 其他实例» [文章]Python学习(十二)

Python学习(十二)

发布人:shili8 发布时间:2025-02-07 07:18 阅读次数:0

**Python 学习(十二)**

**1. 文件操作**

在前面的文章中,我们已经学过了如何使用 Python 来读取和写入文件。然而,文件操作还有一些其他的方面需要我们去了解。

###1.1读取文件我们可以使用 `open()` 函数来打开一个文件,然后使用 `read()` 或 `readline()` 方法来读取文件中的内容。

#读取文件def read_file(filename):
 try:
 with open(filename, 'r') as file:
 content = file.read()
 return content except FileNotFoundError:
 print(f"Sorry, the file {filename} does not exist.")

# 测试函数print(read_file('test.txt'))


###1.2 写入文件我们可以使用 `open()` 函数来打开一个文件,然后使用 `write()` 方法来写入文件中的内容。

# 写入文件def write_file(filename, content):
 try:
 with open(filename, 'w') as file:
 file.write(content)
 except Exception as e:
 print(f"An error occurred: {e}")

# 测试函数write_file('test.txt', 'Hello, world!')


###1.3 追加文件我们可以使用 `open()` 函数来打开一个文件,然后使用 `'a'` 模式来追加内容。

# 追加文件def append_file(filename, content):
 try:
 with open(filename, 'a') as file:
 file.write(content)
 except Exception as e:
 print(f"An error occurred: {e}")

# 测试函数append_file('test.txt', '
Hello, again!')


###1.4 删除文件我们可以使用 `os.remove()` 函数来删除一个文件。

import os# 删除文件def delete_file(filename):
 try:
 os.remove(filename)
 except Exception as e:
 print(f"An error occurred: {e}")

# 测试函数delete_file('test.txt')


**2. 正则表达式**

正则表达式(Regular Expression)是用于匹配字符串模式的特殊字符序列。它可以帮助我们快速找到符合特定规则的文本。

###2.1 匹配模式我们可以使用 `re.match()` 或 `re.search()` 函数来匹配一个模式。

import re# 匹配模式def match_pattern(pattern, string):
 try:
 result = re.search(pattern, string)
 return result.group() if result else None except Exception as e:
 print(f"An error occurred: {e}")

# 测试函数print(match_pattern(r'd{4}', 'Hello,2022!'))


###2.2 替换模式我们可以使用 `re.sub()` 函数来替换一个模式。

import re# 替换模式def replace_pattern(pattern, replacement, string):
 try:
 result = re.sub(pattern, replacement, string)
 return result except Exception as e:
 print(f"An error occurred: {e}")

# 测试函数print(replace_pattern(r'd{4}', '2023', 'Hello,2022!'))


**3. 日期和时间**

我们可以使用 `datetime` 模块来处理日期和时间。

###3.1 获取当前日期我们可以使用 `datetime.now()` 函数来获取当前日期。

import datetime# 获取当前日期def get_current_date():
 try:
 return datetime.date.today()
 except Exception as e:
 print(f"An error occurred: {e}")

# 测试函数print(get_current_date())


###3.2 获取当前时间我们可以使用 `datetime.now()` 函数来获取当前时间。

import datetime# 获取当前时间def get_current_time():
 try:
 return datetime.datetime.now().strftime('%H:%M:%S')
 except Exception as e:
 print(f"An error occurred: {e}")

# 测试函数print(get_current_time())


###3.3 日期加减我们可以使用 `datetime.timedelta()` 函数来加减日期。

import datetime# 日期加减def add_days(date, days):
 try:
 return date + datetime.timedelta(days=days)
 except Exception as e:
 print(f"An error occurred: {e}")

# 测试函数print(add_days(datetime.date.today(),3))


**4. 统计**

我们可以使用 `collections` 模块来统计数据。

###4.1 统计列表我们可以使用 `Counter` 类来统计列表中的元素。

from collections import Counter# 统计列表def count_list(lst):
 try:
 return Counter(lst)
 except Exception as e:
 print(f"An error occurred: {e}")

# 测试函数print(count_list([1,2,3,4,5,6,7,8,9]))


###4.2 统计字典我们可以使用 `Counter` 类来统计字典中的键。

from collections import Counter# 统计字典def count_dict(dct):
 try:
 return Counter(dct.keys())
 except Exception as e:
 print(f"An error occurred: {e}")

# 测试函数print(count_dict({'a':1, 'b':2, 'c':3}))


**5. 并发**

我们可以使用 `threading` 模块来实现并发。

###5.1 创建线程我们可以使用 `Thread` 类来创建一个线程。

import threading# 创建线程def create_thread(target, args=()):
 try:
 thread = threading.Thread(target=target, args=args)
 return thread except Exception as e:
 print(f"An error occurred: {e}")

# 测试函数def test_function():
 print('Hello, world!')

thread = create_thread(test_function)
thread.start()


###5.2 等待线程我们可以使用 `join()` 方法来等待一个线程。

import threading# 等待线程def wait_thread(thread):
 try:
 thread.join()
 except Exception as e:
 print(f"An error occurred: {e}")

# 测试函数thread = create_thread(test_function)
wait_thread(thread)


**6. 异步**

我们可以使用 `asyncio` 模块来实现异步。

###6.1 创建协程我们可以使用 `create_task()` 函数来创建一个协程。

import asyncio# 创建协程def create_coroutine(func):
 try:
 return asyncio.create_task(func)
 except Exception as e:
 print(f"An error occurred: {e}")

# 测试函数async def test_function():
 print('Hello, world!')

coroutine = create_coroutine(test_function)


###6.2 等待协程我们可以使用 `wait()` 函数来等待一个协程。

import asyncio# 等待协程def wait_coroutine(coroutine):
 try:
 return asyncio.wait([coroutine])
 except Exception as e:
 print(f"An error occurred: {e}")

# 测试函数coroutine = create_coroutine(test_function)
result = wait_coroutine(coroutine)


**7. 异常**

我们可以使用 `try`-`except`语句来处理异常。

###7.1 捕获异常我们可以使用 `try`-`except`语句来捕获一个异常。

# 捕获异常def catch_exception(func):
 try:
 return func()
 except Exception as e:
 print(f"An error occurred: {e}")

# 测试函数def test_function():
 raise Exception('Hello, world!')

catch_exception(test_function)


###7.2 抛出异常我们可以使用 `raise` 关键字来抛出一个异常。

# 抛出异常def throw_exception():
 raise Exception('Hello, world!')

throw_exception()


**8. 日志**

我们可以使用 `logging` 模块来实现日志。

###8.1 创建日志我们可以使用 `basicConfig()` 函数来创建一个日志。

import logging# 创建日志def create_logger():
 try:
 logging.basicConfig(level=logging.INFO)
 return logging.getLogger()
 except Exception as e:
 print(f"An error occurred: {e}")

# 测试函数logger = create_logger()


###8.2 记录日志我们可以使用 `info()` 方法来记录一个日志。

import logging# 记录日志def record_log(logger):
 try:
 logger.info('Hello, world!')
 except Exception as e:
 print(f"An error occurred: {e}")

# 测试函数logger = create_logger()
record_log(logger)


**9. 配置**

我们可以使用 `config

相关标签:python开发语言
其他信息

其他资源

Top