python打开文件为什么不全部执行呢


with open('learning_python.txt') as learning_python :
    print(learning_python.read())
    for line in learning_python:
        print(line)

为什么不全部执行呢

img


如图,为什么只执行第一行呢

题主您好,我刚才试了一下你的代码,是可以打印的,但是不够规范,您看看这个

    with open(r'C:\Users\17591\Desktop\a.txt', "r+", encoding="UTF-8") as learning_python:
        # print(learning_python.read())
        for line in learning_python.readlines():
            print(line)

readlines 表示将每行内容存入列表中,然后line打印出来

指针已经跑到文件最后了,你会发现,即使后面再写什么也是只有一遍得读取了,而且后面不管你写什么程序都会结束的,除非跳出第一个文件打开重新打开并阅读文件,或者使用learning_python. seek(0)复位

with open('learning_python.txt','r') as f:
    print(f.read)
    f. seek(0)
    for line in f:
        print(line)