09-python--file

'''
open内置函数,调用的是操作系统的接口
f1变量:文件句柄,对文件的任何操作都得通过文件句柄进行
encoding:可以不写,默认编码:操作系统的默认编码
windows:gbk
linux/mac:utf-8
'''
'''
1、打开文件
2、操作文件句柄
3、关闭文件
'''
#
# read
'''
f1 = open('gpg.txt')
content = f1.read() # 全部读
content = f1.read(7) # 按照字符读
content = f1.readline() # 按行读
content = f1.readlines() # 返回一个列表,列表中的每个元素是列表中的每一行
print(content)
f1.close()

for 读取
f = open('gpg.txt')
for line in f:
print(line)
f.close()

rb:操作的是非文本的文件,图片、视频、音频
f = open('ggg.png', mode='rb')
content = f.read()
print(content)
f.close()

# r+:读并追加
f = open('rjia.txt', encoding='utf-8', mode='r+')
content = f.read()
print(content)
f.write('sd')
f.close()
'''

# write:如果文件存在,先清空文件内容,再写入
'''
f = open('ggg.txt', mode='w', encoding='utf-8')
f.write('你好')
f.close()

# wb
f1 = open('ggg.png', mode='rb')
content = f1.read()
f1.close()

f2 = open('gggg.png', mode='wb')
f2.write(content)
f2.close()
'''

# append:有文件在原文件后追加,没有则创建
# f = open('333.txt', mode='a', encoding='utf-8')
# f.write('hello\n')
# f.close()

# tell:光标位置,按字节
# f = open('rjia.txt', encoding='utf-8')
# print(f.tell())
# content = f.read()
# print(f.tell())
# f.close()

# seek:调整光标位置
# f = open('rjia.txt', encoding='utf-8')
# print(f.seek(4))
# content = f.read()
# print(content)
# f.close()

# flush:强制刷新
# f = open('rjia.txt', encoding='utf-8', mode='w')
# f.write('asdasdasd')
# f.flush()
# f.close()

# with open('333.txt', encoding='utf-8') as f1:
# print(f1.read())

# with open('333.txt', encoding='utf-8') as f1, \
# open('rjia.txt', encoding='utf-8',mode='w') as f2:
# print(f1.read())
# f2.write('dffsd')

'''
文件修改步骤:
1、以读的模式打开源文件
2、以写的模式创建一个新文件
3、将源文件的内容读取并修改成你想要的新内容,并写入新文件
4、将源文件删除
5、将新文件重命名成源文件
'''

# import os
# with open('333.txt', encoding='utf-8') as f1, \
# open('333bak.txt', encoding='utf-8',mode='w') as f2:
# old_content = f1.read()
# new_content = old_content.replace('hello', 'dfl')
# f2.write(new_content)
# os.remove('333.txt')
# os.rename('333bak.txt', '333.txt')

# import os
# with open('333.txt', encoding='utf-8') as f1, \
# open('333bak.txt', encoding='utf-8',mode='w') as f2:
# for line in f1:
# # old_line = line.strip()
# new_line = line.replace('dfl', 'bbbbb')
# f2.write(new_line)
# os.remove('333.txt')
# os.rename('333bak.txt', '333.txt')
posted @ 2020-04-28 12:05  Daspig  阅读(417)  评论(0编辑  收藏  举报