文件调用函数open
1、以读方式打开一个文件对象,当文件不存在时,会抛出一个FileNotFoundError
f = open('a.txt','r') f.read() f.close()
Traceback (most recent call last): File "F:/vicpy/std/day1/login.py", line 3, in <module> f = open('b.txt','r') FileNotFoundError: [Errno 2] No such file or directory: 'b.txt'
2、以写方式打开一个文件对象,当文件不存在时,会自动创建此文件
f = open('a.txt','w') f.write("hello") f.close()
3、open函数简单使用
f1 = open('a.txt','w') f1.write("hello world!\n") f1.write("welcome!!!") f1.close() f2 = open('a.txt','r') a = f2.read() print(a) f2.close()
hello world!
welcome!!!