如何在阅读文件时打印某些信息?

时间:2016-01-29 20:04:41

标签: python python-3.x

所以我在python中有这段代码:

payment = open ("paintingJobs.txt" , "r")
lines = payment.readlines()
print (lines), ["A"]

[作业] [1]

并且,我试图仅以适当的格式(不是邋)打印包含" A" 的文档行。 我已尝试过上面的代码,但它只是以无组织的方式打印出整个文档。

有没有办法像这样展示打印的信息:Table

2 个答案:

答案 0 :(得分:0)

print (lines), ["A"]不是打印包含字母A的lines的每个元素的正确语法。请尝试:

payment = open ("test.py" , "r")
lines = payment.readlines()
for line in lines:
    if "A" in line:
        print(line)
payment.close()

或者,或者,

payment = open ("test.py" , "r")
lines = payment.readlines()
print([line for line in lines if "A" in line])
payment.close()

答案 1 :(得分:0)

您已使用with

with open("test.py" , "r") as payment
    lines = payment.readlines()
    print([line for line in lines if "A" in line])