30 文件操作

#1 打开文件,open 函数
file1 = open("test2.py")

#2读取文件,read
text = file1.read()    #返回字符串类型

print(text)

#3 关闭文件
file1.close()

 

#
file1 = open("test2.py")


text = file1.read()
print(text)
print(len(text))    #打印读取的长度

print("-"*50)

text = file1.read()
print(text)
print(len(text))    


file1.close()

执行结果:   第二次什么也没读到,因为第一次read 完成,文件指针在最后面

test
test
test
14
--------------------------------------------------

0   

 

大文件,循环读取一行:

#
file1 = open("test2.py")

while True:
    text = file1.readline()

    
    #if not text:
    #if text == '':
    if  len(text)== 0:
        break

    print(text)

file1.close()

 

posted @ 2020-06-12 22:59  abel2020  阅读(118)  评论(0编辑  收藏  举报