写一段代码python,统计目录下的所有文件,一共多少行包含log字段
时间: 2024-05-31 15:08:29 浏览: 7
import os
directory = "/path/to/directory" # 替换为目标目录的路径
log_count = 0
line_count = 0
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith(".txt"): # 只统计txt文件
with open(os.path.join(root, file), "r") as f:
lines = f.readlines()
for line in lines:
if "log" in line:
log_count += 1
line_count += 1
print(f"目录 {directory} 下共有 {line_count} 行代码,其中包含 log 字段的行数为 {log_count} 行。")
相关问题
写一段python代码 搜索整个文件目录下c文件
好的,以下是您需要的 python 代码:
``` python
import os
# 遍历文件夹下的所有文件
for root, dirs, files in os.walk("."):
for file in files:
# 判断是否为 c 文件
if file.endswith(".c"):
# 输出文件路径
print(os.path.join(root, file))
```
请注意,此代码仅搜索当前文件夹及其子文件夹下的 c 文件,并且不会搜索压缩文件等非文本文件。如果您需要更复杂的搜索,您可能需要使用更高级的库或自己编写更多的代码。
帮我写一段Python代码要求如下:统计CSV文件中数据所有个数
好的,以下是统计CSV文件中数据所有个数的Python代码示例:
```python
import csv
# 打开CSV文件
with open('data.csv', 'r') as file:
# 读取CSV文件数据
reader = csv.reader(file)
# 统计数据个数
count = sum(1 for row in reader for _ in row)
# 输出数据个数
print(f'Total count: {count}')
```
这段代码中,我们使用Python内置的csv库来读取CSV文件,通过两层循环遍历每一行和每一列,然后使用sum函数统计数据个数,并输出结果。需要注意的是,在执行`sum`函数之前必须要将文件指针移动到文件开头(或者使用`file.seek(0)`)以重新开始读取文件内容。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)