写一个python脚本,计算文件行数,
时间: 2024-04-29 15:25:33 浏览: 18
可以使用以下代码来计算文件的行数:
```python
filename = input("请输入文件名:")
count = 0
with open(filename, 'r') as f:
for line in f:
count += 1
print("文件共有%d行。" % count)
```
说明:
1. 通过`input`函数获取用户输入的文件名。
2. 使用`with open`语句打开文件,并以只读模式(`'r'`)读取文件内容。
3. 遍历文件对象`f`,每遍历一行,计数器`count`加1。
4. 打印输出文件的行数。
相关问题
写一个python脚本,计算文件行数,删除空行个以双斜杠开头的行
以下是一个Python脚本,可以计算文件行数,并删除空行和以双斜杠开头的行:
```python
filename = input("请输入文件名:")
# 统计文件行数
with open(filename, 'r', encoding='utf-8') as f:
lines = f.readlines()
total_lines = len(lines)
print("文件总共有{}行。".format(total_lines))
# 删除空行和以双斜杆开头的行
new_lines = []
for line in lines:
line = line.strip() # 去除行首和行尾的空格和换行符
if line and not line.startswith('//'): # 非空行且不以双斜杆开头
new_lines.append(line)
# 写入新文件
new_filename = 'new_' + filename
with open(new_filename, 'w', encoding='utf-8') as f:
f.write('\n'.join(new_lines))
print("删除空行和以双斜杆开头的行后,新文件总共有{}行。".format(len(new_lines)))
```
这个脚本首先要求用户输入文件名,然后使用`open()`函数打开文件,读取所有行,统计总共行数。
接下来,使用一个循环遍历每一行,去除行首和行尾的空格和换行符,然后判断是否为空行或以双斜杆开头。如果不是,则将这一行添加到一个新的列表中。最后,使用`join()`函数将新列表中的所有行合并成一个字符串,写入一个新的文件中。
运行脚本后,会先询问用户要处理哪个文件。然后会输出文件总共有多少行,以及删除空行和以双斜杆开头的行后,新文件总共有多少行。同时,新文件将会被保存在原文件名前面加上`new_`的文件名中。
用Python写一个脚本,找到Verilog中例化的子模块,并统计器代码行数
好的,我可以为您提供一些思路和代码示例。首先,您可以使用Python的正则表达式模块来查找Verilog文件中的所有模块实例。然后,您可以使用Python的文件操作功能来打开每个子模块文件并计算其代码行数。
以下是一个可能的实现示例:
```python
import re
import os
# 正则表达式匹配模块实例
module_instance_pattern = re.compile(r'\s+(\w+)\s+(\w+)\s*\(')
# 统计代码行数的函数
def count_lines(file_path):
with open(file_path, 'r') as f:
return len(f.readlines())
# 遍历Verilog文件夹并查找子模块
verilog_folder = './verilog/'
for file_name in os.listdir(verilog_folder):
if file_name.endswith('.v'):
file_path = os.path.join(verilog_folder, file_name)
with open(file_path, 'r') as f:
content = f.read()
# 查找模块实例
module_instances = module_instance_pattern.findall(content)
for module_instance in module_instances:
module_name = module_instance[0]
instance_name = module_instance[1]
# 打开子模块文件并统计代码行数
module_path = os.path.join(verilog_folder, module_name + '.v')
if os.path.exists(module_path):
line_count = count_lines(module_path)
print(f"{instance_name} -> {module_name}: {line_count} lines")
```
您可以将上述代码保存为一个Python脚本,并在命令行中运行它,即可查找Verilog文件夹中所有模块实例,并统计其代码行数。
需要注意的是,上述代码仅是一个示例,您可能需要根据实际情况进行修改和优化。例如,您可能需要考虑多层嵌套模块实例的情况,以及文件路径的处理方式等。
相关推荐
![](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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)