分别采用open-close、with-open两种方式,将自己的学号、姓名、班级等信息分行写入文本文件a.txt中;

分别采用open-close、with-open两种方式,将自己的学号、姓名、班级等信息分行写入文本文件a.txt中;

分别采用open-close、with-open两种方式,读取文本文件a.txt中的全部内容并输出

分别采用open-close、with-open两种方式,读取文本文件a.txt中的前3个字符并输出;

f = open("a.txt", "w")  # open-close写入
f.write("学号:001,姓名:小明,班级:数学201,性别:男")
f.close()

with open("a.txt","w") as f:  # with-open写入
    f.write("学号:001,姓名:小明,班级:数学201,性别:男")
    f.close()

f = open("a.txt", "r")  # open-close输出
print(f.read())
f.close()

with open("a.txt", "r") as f:  # with-open输出
    print(f.read())
    f.close()

f = open("a.txt", "r")  # open-close输出3个字符
print(f.read(3))
f.close()

with open("a.txt", "r") as f:  # with-open输出3个字符
    print(f.read(3))
    f.close()

猜你喜欢

转载自blog.csdn.net/weixin_51343683/article/details/109133871
今日推荐