Python代码大全:40个实用代码片段260


简介

Python因其简洁的语法、强大的库和广泛的用途而广受欢迎。本文汇编了40个实用且通用的Python代码片段,涵盖了文件处理、字符串操作、数据分析和更多内容。这些代码片段精心挑选,旨在提高您的编程效率和解决常见问题的速度。

1. 读取文件

```python
with open("", "r") as f:
lines = ()
```

将文本文件的所有行读取到一个列表中。

2. 写入文件

```python
with open("", "w") as f:
("写出到文件的内容")
```

将指定内容写入文本文件。

3. 获取文件大小

```python
import os
filesize = ("")
```

获取文件的大小(以字节为单位)。

4. 判断文件是否存在

```python
import os
("")
```

检查文件是否存在。

5. 遍历目录

```python
import os
for dirpath, dirnames, filenames in ("directory_path"):
print(dirpath)
```

遍历目录及其子目录并打印目录路径。

6. 查找字符串

```python
"my_string".find("substring")
```

在字符串中查找子字符串并返回其第一次出现的索引位置(如果未找到,则返回-1)。

7. 替换字符串

```python
"my_string".replace("old", "new")
```

将字符串中的子字符串替换为新的子字符串。

8. 连接字符串

```python
"my_string" + " another_string"
```

连接两个字符串。

9. 格式化字符串

```python
"my_value = {}".format(value)
```

使用占位符格式化字符串。

10. 分割字符串

```python
"my_string".split(" delimiter ")
```

使用指定的定界符将字符串分割为一个列表。

11. 创建列表

```python
my_list = [1, 2, 3]
```

创建一个列表。

12. 访问列表元素

```python
my_list[index]
```

使用索引访问列表中的元素。

13. 添加列表元素

```python
(item)
```

将元素添加到列表的末尾。

14. 删除列表元素

```python
del my_list[index]
```

使用索引删除列表中的元素。

15. 排序列表

```python
()
```

对列表中的元素进行排序。

16. 创建字典

```python
my_dict = {"key1": "value1", "key2": "value2"}
```

创建一个字典。

17. 访问字典值

```python
my_dict["key"]
```

使用键访问字典中的值。

18. 添加字典键值对

```python
my_dict["new_key"] = "new_value"
```

向字典中添加一个新的键值对。

19. 删除字典键值对

```python
del my_dict["key"]
```

使用键删除字典中的键值对。

20. 获取字典键

```python
()
```

获取字典中所有键的列表。

21. 获取字典值

```python
()
```

获取字典中所有值的列表。

22. 检查列表中元素

```python
"item" in my_list
```

检查列表中是否包含指定元素。

23. 检查字典中键

```python
"key" in my_dict
```

检查字典中是否包含指定键。

24. 创建元组

```python
my_tuple = (1, 2, 3)
```

创建一个元组。

25. 访问元组元素

```python
my_tuple[index]
```

使用索引访问元组中的元素。

26. 创建集合

```python
my_set = {1, 2, 3}
```

创建一个集合。

27. 添加集合元素

```python
(item)
```

将元素添加到集合中。

28. 删除集合元素

```python
(item)
```

使用元素从集合中删除元素。

29. 检查集合中元素

```python
item in my_set
```

检查集合中是否包含指定元素。

30. 获取集合长度

```python
len(my_set)
```

获取集合中的元素数量。

31. 计算平方根

```python
import math
(number)
```

计算指定数字的平方根。

32. 生成随机数

```python
import random
()
```

生成0到1之间的随机数。

33. 获取当前时间

```python
import datetime
()
```

获取当前日期和时间。

34. 格式化日期

```python
import datetime
().strftime("%Y-%m-%d %H:%M:%S")
```

使用指定格式将日期和时间格式化为字符串。

35. 读取命令行参数

```python
import sys
```

获取传递给脚本的命令行参数。

36. 创建函数

```python
def my_function(parameter1, parameter2):
"""函数文档"""
# 函数代码
```

创建一个函数。

37. 调用函数

```python
my_function(argument1, argument2)
```

调用函数并传递参数。

38. 处理异常

```python
try:
# 可能会引发异常的代码
except Exception as e:
# 异常处理代码
```

使用try-except块处理异常。

39. 创建类

```python
class MyClass:
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1
self.attribute2 = attribute2
```

创建一个类。

40. 创建类对象

```python
my_object = MyClass(value1, value2)
```

创建一个类对象。

2024-10-28


上一篇:Python 通过 MySQLdb 库查询 MySQL 数据库

下一篇:数字转换为字符串:在 Python 中巧妙沟通