python调用Linux统计文件行数和大小
时间: 2025-01-25 22:14:48 浏览: 37
在Python中调用Linux命令来统计文件行数和大小是非常方便的。你可以使用`subprocess`模块来执行Linux命令。以下是一个示例代码,展示了如何统计文件的行数和大小:
```python
import subprocess
def count_lines(file_path):
try:
# 使用wc -l命令统计文件的行数
result = subprocess.run(['wc', '-l', file_path], capture_output=True, text=True)
line_count = int(result.stdout.strip().split()[0])
return line_count
except Exception as e:
print(f"Error counting lines: {e}")
return None
def get_file_size(file_path):
try:
# 使用stat -c %s命令获取文件大小(字节)
result = subprocess.run(['stat', '-c', '%s', file_path], capture_output=True, text=True)
file_size = int(result.stdout.strip())
return file_size
except Exception as e:
print(f"Error getting file size: {e}")
return None
# 示例文件路径
file_path = 'example.txt'
# 统计行数
line_count = count_lines(file_path)
if line_count is not None:
print(f"The file {file_path} has {line_count} lines.")
# 获取文件大小
file_size = get_file_size(file_path)
if file_size is not None:
print(f"The file {file_path} is {file_size} bytes in size.")
```
在这个示例中,我们定义了两个函数:`count_lines`和`get_file_size`。`count_lines`函数使用`wc -c %s`命令来获取文件的大小。最后,我们调用这两个函数并打印结果。
阅读全文
相关推荐


















