python 读取文件,过滤注释行
时间: 2023-10-17 17:16:47 浏览: 66
以下是一个示例代码,它可以从文件中读取文本,过滤注释行,并将其打印到控制台上:
```python
with open("filename.txt", "r") as file:
for line in file:
# 如果行以#开头,则跳过
if line.startswith("#"):
continue
# 否则,打印该行
print(line.strip())
```
这个代码使用了Python的文件读取功能,使用`open()`函数打开文件,并将其存储在一个变量中。然后,使用`for`循环逐行读取文件中的内容。如果该行以`#`开头,则使用`continue`语句跳过该行。否则,使用`print()`函数打印该行。`strip()`函数用于去掉该行中的空格、制表符和换行符等空白字符。
相关问题
python 读取整行的数字
你可以使用 Python 的文件操作来读取整行的数字。下面是一个示例代码:
```python
with open('file.txt', 'r') as f:
for line in f:
numbers = list(map(int, line.split()))
print(numbers)
```
在这个示例代码中,我们打开了一个名为 `file.txt` 的文件,并逐行读取它。对于每一行,我们使用 `split()` 方法将它分割成数字字符串,并使用 `map()` 函数将它们转换为整数。最后,我们将这些整数打印出来。
请注意,这个示例代码假设每行只包含数字,如果你的文件中有其他内容(例如注释或空格),你需要在读取行时进行过滤。
Python 读取1.txt文件中的内容,去除空行和注释行后,以行为单位进行排序,并将结果输出到2.txt文件中
可以使用以下代码实现:
```python
# 定义注释符号
comment_symbol = '#'
# 打开1.txt文件和2.txt文件
with open('1.txt', 'r') as f1, open('2.txt', 'w') as f2:
# 读取1.txt文件中的所有行
lines = f1.readlines()
# 过滤掉空行和注释行,并按行为单位进行排序
filtered_lines = sorted(filter(lambda x: x.strip() and not x.startswith(comment_symbol), lines))
# 将结果输出到2.txt文件中
f2.writelines(filtered_lines)
```
代码解释:
首先定义了注释符号,然后使用 `with` 语句打开1.txt文件和2.txt文件。使用 `readlines()` 方法读取1.txt文件中的所有行,并将它们存储在一个列表中。接着使用 `filter()` 函数和 lambda 表达式过滤掉空行和注释行,使用 `sorted()` 函数按行为单位进行排序。最后使用 `writelines()` 方法将结果写入到2.txt文件中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![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)