python - 从文件中读取以特定字符开头的每一行

标签 python

我正在尝试读取以“X:”开头的文件中的每一行。我不想只阅读“X:”本身,而只是阅读后面一行的其余部分。

with open("hnr1.abc","r") as file: f = file.read()
id = []
for line in f:
    if line.startswith("X:"):
        id.append(f.line[2:])
print(id)

它没有任何错误,但它没有打印出任何东西。

最佳答案

试试这个:

with open("hnr1.abc","r") as fi:
    id = []
    for ln in fi:
        if ln.startswith("X:"):
            id.append(ln[2:])
print(id)

不要使用文件或行之类的名称

注意附加只是使用项目名称而不是文件的一部分

通过将文件预读入内存,for 循环按字符而不是按行访问数据

关于python - 从文件中读取以特定字符开头的每一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33149152/

相关文章:

python - python中多个条件的if then else语句

python - 如何在Python中使用tkinter按钮终止两个进程

python - 在 excepthook 中打印原始异常

python - 在 Python 中初始化大量 boolean 值

python - 在numpy记录数组中如何访问python中的某些元素值

python - 用于交叉验证的附加拟合参数

python - python 无法连接 mongodb

python - 计算 Python 数组中的值

c# - 如何从 C# 将任务排队到 Celery?

python - 从列表框项中获取文本