为什么我的脚本不打印 hello.txt 文件的第一行?



我在python中写了一个脚本,然后在命令行中运行它。输出的第一部分是我期望的。但是,它不会像我想要的readline()那样打印第一行。我被问到第二个问题,但是当我回答"是"时,它会打印一条空线。当我删除IF语句和第一个问题时,它可以正常工作,但是我无法与IF语句一起使用。这是脚本:

script, filename = argv
print("I'm going to open the file.")
txt1 = open(filename) 
question1 = raw_input("Do you wanna see the content? ")

if (question1 == "yes" or question1 == "Yes"):
   print(txt1.read())
question2 = raw_input("Do you want me to read just the first line? ")
if (question2 == "yes" or question2 == "Yes"):
   print(txt1.readline())

预先感谢。

open()返回的文件对象跟踪您所在的文件中的位置。您对txt1.read()进行的第一个呼叫将读取整个文件,并将您在文件中的位置推进到最后。如果要重置为文件的开头,则可以在再次从文件中阅读之前进行txt1.seek(0)

您可能想做

txt1.seek(0)

在两个读物之间。这将您当前的位置重置为文件的开始。

更好的样式将是

if (question1 == "yes" or question1 == "Yes"):
    with open(filename) as txt1:
        print(txt1.read())

最新更新