(一)文件操作
1.read()会一次性读取文件的全部内容
file=open('aa.txt','r')
a=file.read()
print(b)
a.close
2.readline() 每次读取一行,并且自带换行功能 每一行末尾会读到\n
a=open('d:\\python\\day0801\\aa.txt','r')
b=a.readline()
while len(b)>0:
print(b)
b=a.readline()
a.close()
3.Readlines() 一次性以行的形式读取文件的所有内容并返回一个list,需要遍历读出来
a=open('d:\\python\\day0801\\aa.txt','r')
b=a.readlines()
print(b)
for x in b:
print(x)
a.close
4.循环读取
file句柄是一个可迭代的对象因此,可以循环读取文件中的内容,每次读一行
for x in open("d:\\python\\day0801\\aa.txt",'r'):
print(x)
(二)写操作
1.write 一次性全部写入
a=open('d:\\python\\day0801\\aa.txt',mode='w')
a.write('111111')
a.close
2.writelines 把内容全部写到文件中(多行一次性写入)
ls=['aa','b\n','cc']
a=open('d:\\python\\day0801\\bb.txt','w')
a.writelines(ls)
a.close()
with 使用with方法操作文件,可以不用关闭文件,会自动关闭文件
with open('d:\\python\\day0801\\bb.txt','r') as f:
b=f.read()
print(b)
(三)os模块
重命名文件 os. rename(src,dst)
impore os
os.rename('test.txt','test1.txt')
删除文件 os.remove(path)
0s.remove('test1.txt') #要删除文件,如果是目录报错
创建目录 mkdir()生成单层目录
os.mkdir('aa')
创建多级目录
os.makedirs('a\\b\\c\\d')