1.文件基本操作
2.写入数据
f = open('test1.txt','w',encoding = 'utf-8')
f.write('哈喽你好')
f.close()
3.读取数据
f = open('test1.txt','r',encoding = 'utf-8')
print(f.read())
f.close()
4.追加写入
f = open('test1.txt','a',encoding = 'utf-8')
f.write('你真好玩')
f.close()
f = open('test1.txt','w',encoding = 'utf-8')
f.write('你是来开玩笑的吗?')
f.close()
5.文件路径
f.close()
f=open('../class06/test1.txt','r',encoding='utf-8')
print(f.read())
f.close()
f = open(r'C:\Users\user\PycharmProjects\cema\class06\test1.txt','r',encoding='utf-8')
print(f.read())
f.close()
6.访问模式 r w a r+ w+ a+
f = open('test1.txt','r+',encoding='utf-8')
print(f.read())
f.close()
f = open('test1.txt','r+',encoding='utf-8')
print(f.tell())
f.seek(0,1)
print(f.tell())
f.write('司小幽')
f.close()
f = open('test1.txt','w+',encoding='utf-8')
print(f.tell())
f.seek(0,2)
f.write('你好,妈妈咪呀')
f.close()
f = open('test1.txt','a+',encoding='utf-8')
print(f.tell())
f.seek(0,0)
f.write('\n我是来追加的')
f.close()
7.读取操作
f=open('test1.txt','r',encoding='utf-8')
print(f.readlines()[1])
f.close()
8.读取文件的方式
with open('test1.txt','r',encoding='utf-8') as f:
print(f.read())
9.文件和文件夹的操作
import os
file=r'C:\Users\user\PycharmProjects\cema\class06\sixiaoyou'
print(os.path.isfile(file))
print(os.getcwd())
print(__file__)
print(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
a = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),'config')
print(a)
print(a+'\conf.ini')
print(a+'\info.yaml')