Day8 文件

文件操作
创建文件,不可读
f = open(file='文件操作.txt',mode='w')
f.write('qiangzi it 175 80 2000\nxifeng it 185 70 4000\n')
f.close()

只读文件,不能写
f = open(file='文件操作.txt',mode='r')
# print(f.read())
print(f.readline())
data = f.read()
print(data)
f.close()

添加文件,不能读
f = open(file='文件操作.txt',mode='a')
f.write('daqiang it 182 75 6000\nloangzong boss 170 75 1000000\nchao it 180 78 8000\nsunqiang it 170 70 8000')
f.close()

#文件循环 for循环
f = open(file='文件操作.txt',mode='r')
for line in f:
line = (line.split())
height = int(line[2])
weight = int(line[3])
if height > 175 and weight > 75:
print(line)



file类的其他的必要功能
#.seek  把光标移到哪个位置 3字节一中文
f = open(file='文件操作.txt')
f.seek(6)
print(f.read())


.flush 强制把缓存里的数据刷到硬盘里
tell 返回光标的位置
f = open(file='文件操作.txt')
f.seek(6)
print(f.read())
print(f.tell())

i it 175 80 2000
xifeng it 185 70 4000
daqiang it 182 75 6000
loangzong boss 170 75 1000000
chao it 180 78 8000
sunqiang it 170 70 8000

154

truncate()  截取

# f = open(file='文件操作.txt',mode='w')
# f.write('qiangzi it 175 80 2000\nxifeng it 185 70 4000\n')
# f.close()
#
#
# f = open(file='文件操作.txt',mode='r')
# # print(f.read())
# print(f.readline())
# data = f.read()
# print(data)
# f.close()
#
#
# f = open(file='文件操作.txt',mode='a')
# f.write('daqiang it 182 75 6000\nloangzong boss 170 75 1000000\nchao it 180 78 8000\nsunqiang it 170 70 8000')
# f.close()

#文件循环
# f = open(file='文件操作.txt',mode='r')
# for line in f:
# line = (line.split())
# height = int(line[2])
# weight = int(line[3])
# if height > 175 and weight > 75:
# print(line)

# #seek 把光标移到哪个位置 3字节一中文
# f = open(file='文件操作.txt')
# f.seek(6)
# print(f.read())
# print(f.tell())

# import os
# old_file = '文件操作1.txt'
# new_file = '文件操作1.txt.new'
# f = open(file=old_file,mode='r')
# f_new = open(file=new_file,mode='w')
# for line in f:
# old_str = 'it'
# new_str = 'big boss'
# if 'it' in line:
# line = line.replace(old_str,new_str)
# else:
# line = line
# f_new.write(line)
# f.close()
# f_new.close()
# os.replace('文件操作1.txt.new','文件操作1.txt')



# import os
# old_file = '文件操作.txt'
# new_file = '文件操作.txt.new'
# f = open(file=old_file,mode='r')
# f_new = open(file=new_file,mode='w')
# old_str = 'it'
# new_str = 'big big boss'
# for line in f:
# if old_str in line:
# line = line.replace(old_str,new_str)
# f_new.write(line)
# f.close()
# f_new.close()
# os.replace(new_file,old_file)





猜你喜欢

转载自www.cnblogs.com/wzq1997/p/12945556.html