文件的基本操作
1、打开和读写
mode:
r:只能读文件
w:只能写入(清空文件内容)
a+:读写(文件最后追加写入内容)
追加内容:
执行以下代码:
f = open('hello.txt',mode='a') ##打开文件
f.write('java\n') ##文件读写操作
f.close() ##关闭文件
追加内容成功
2、关闭文件
with语句
with语句在执行完后会自动关闭文件:
此代码输出为空:
with open('hello.txt',mode='w+') as f:
f.write('hello world\n')
print(f.read())
因为在写完内容之后,指针在最后,而读的操作是在指针当前位置往后读的,所以没有输出。
将指针移动到最开始:
with open('hello.txt',mode='w+') as f:
f.write('hello world\n')
f.seek(0,0) ##将指针移动到最开始
print('当前指针位置:',f.tell())
print(f.read())
输出成功: