文件的操作

#文本以什么编码编辑就以什么编码去读加b以bash方式去读
# f = open('text.txt', mode='r', encoding='UTF-8')
# context = f.read()
# print(context)
# f.close()

#写时,如果文件名不存在则建立,如果存在则删除内容再写进去
# f = open('text.txt', mode='w', encoding='UTF-8')
# f.write('我爱你')
# f.close()

#以bytes方式写,一般是非文本文件如图片等
# f = open('text.txt', mode='wb')
# f.write('我爱你'.encode('UTF-8'))
# f.close()


#追加方式mode='a'
# f = open('text.txt', mode='a', encoding='UTF-8')
# f.write('我爱你123')
# f.close()


#r+先读再写,光标读完移到最后再写
# f = open('text.txt', mode='r+', encoding='UTF-8')
# print(f.read())
# f.write('qqq')
# f.close()

#r+先写再读,光标是从0开始写,读是从光标后开始读
# f = open('text.txt', mode='r+', encoding='UTF-8')
# f.write('qqq')
# f.seek(0)
# print(f.read())
# f.close()


#w+先删除再写
# f = open('text.txt', mode='a+', encoding='UTF-8')
# f.write('我爱你1')
# f.seek(0)
# print(f.read())
# f.close()

#readline一行一行的读,readlines将每一行读出来作为列表的元素
f = open('text.txt', mode='r', encoding='UTF-8')
print(f.read(6))                #read是字符,所以输出6个字符
f.seek(3)                       #按照字节定光标位置,一个中文3个字节
print(f.tell())                 #tell定位光标位置
print(f.read())
print(f.writable())             #是否可写
f.close()
原文地址:https://www.cnblogs.com/hhsh/p/9503175.html