欢迎访问宙启技术站
智能推送

Python中的常见util函数汇总

发布时间:2024-01-17 17:21:55

Python中有很多常见的util函数,这些函数可以帮助我们更方便地处理一些常见的任务。下面是一些常见的Python util函数及其使用示例:

1. os.path.exists(path):检查指定路径的文件或目录是否存在,存在返回True,否则返回False。

import os

path = '/path/to/file.txt'
if os.path.exists(path):
    print('文件存在')
else:
    print('文件不存在')

2. os.path.join(path1, path2):连接两个或多个路径组件,返回一个新的路径字符串。

import os

path1 = '/path/to'
path2 = 'file.txt'
new_path = os.path.join(path1, path2)
print(new_path)  # 输出:'/path/to/file.txt'

3. os.path.basename(path):返回指定路径中的文件名部分。

import os

path = '/path/to/file.txt'
filename = os.path.basename(path)
print(filename)  # 输出:'file.txt'

4. os.path.dirname(path):返回指定路径中的目录部分。

import os

path = '/path/to/file.txt'
directory = os.path.dirname(path)
print(directory)  # 输出:'/path/to'

5. os.listdir(path):返回指定目录下的所有文件和目录的列表。

import os

path = '/path/to'
files = os.listdir(path)
print(files)  # 输出:['file1.txt', 'file2.txt', 'directory']

6. shutil.copyfile(src, dst):将文件从源路径复制到目标路径。

import shutil

src = '/path/to/source/file.txt'
dst = '/path/to/destination/file.txt'
shutil.copyfile(src, dst)

7. shutil.rmtree(path):递归删除指定目录以及其内容。

import shutil

path = '/path/to/directory'
shutil.rmtree(path)

8. re.compile(pattern):将正则表达式模式编译成正则表达式对象,可用于提高正则表达式的效率。

import re

pattern = re.compile(r'\d+')
result = pattern.search('abc123')
print(result.group())  # 输出:'123'

9. datetime.datetime.now():获取当前日期和时间。

import datetime

now = datetime.datetime.now()
print(now)  # 输出:'2021-01-01 12:00:00'

10. random.choice(seq):从序列中随机选择一个元素。

import random

seq = ['apple', 'banana', 'orange']
choice = random.choice(seq)
print(choice)  # 输出:随机选择的一个元素

这些只是Python中一些常见的util函数及其使用示例,实际上还有很多其他有用的函数,可以根据具体需求来选择使用。