python入门基础-文件操作

1.文件操作-内容读

#文件读 r ,相对路径读取内容的方式
read_file = open('天气预报',mode='r',encoding='utf-8')
content = read_file.read()
print(content)
read_file.close()

#文件读 r ,绝对路径读取内容的方式
read_file = open(r'H:\tak\a.txt',mode='r',encoding='gbk')
content = read_file.read()
print(content)
read_file.close()

#文件读 rb ,rb bytes方式读入
read_file = open(r'H:\tak\a.txt',mode='rb')
content = read_file.read()
print(content)
read_file.close()

2.文件操作-内容写

#文件写 w ,相对路径写入内容的方式(没有此文件系统会创建,如果有内容,会清空在继续写入)
# write = open('log',mode='w',encoding='utf-8')
# write.write('今天是个好日子!')
# write.close()

#文件写 wb :
# f = open('log',mode='wb')
# f.write('write file'.encode('utf-8'))
# f.close()

3.文件操作-内容追加

#文件追加 a:
f = open('log',mode='a',encoding='utf-8')
f.write('\nnew')
f.close()

#文件追加 rb:
f = open('log',mode='ab')
f.write('\n天天向上'.encode('utf-8'))
f.close()

4.文件操作-内容读写

#文件读写 r+ :读写可正常追加内容,读写(先write 后read)会覆盖
f = open('log',mode='r+',encoding='utf-8')
f.read()
f.write('\n好好学习')
f.seek(0)
print(f.read())
f.close()

#文件读写 r+b :
f = open('log',mode='r+b')
print(f.read())
f.write('与时代共同进步'.encode('utf-8'))
f.close()

5.文件操作-内容写读

#文件写读 w+:
f = open('log',mode='w+',encoding='utf-8')  #会覆盖文件中原有内容!
f.write('\n圣诞节快乐哈!')
f.seek(0)   #光标移动到最前面!
print(f.read())
f.close()

#文件写读 w+b:
f = open('log',mode='w+b')
f.write('\n交换式电源供电'.encode('utf-8'))
f.seek(0)
print(f.read())
f.close()

6.文件操作-内容追加读

#文件追加 a+ :
f = open('log',mode='a+',encoding='utf-8')
f.write('\n新时代广场')
f.seek(0)
print(f.read())
f.close()

#文件追加  a+b :
f = open('log',mode='a+b')
f.write('\n时尚周刊'.encode('utf-8'))
f.seek(0)
print(f.read())
f.close()

7.文件操作-with读入

#with 读入文件,省去最后的close动作
with open('log',mode='r',encoding='utf-8') as f:    #打开一个文件的方式
    print(f.read())


with open('log',mode='r',encoding='utf-8') as f,\
    open('user_config.cnf',mode='r',encoding='utf-8') as f1:    #同时打开两个文件的方式
    print(f.read())
    print(f1.read())

8.部分方法介绍

#部分功能介绍
f = open('log',mode='r',encoding='utf-8')
print(f.read(3))    #read中的参数3,表示读取光标后的3个“字符”
f.seek(3)   #是按“字节”移动光标到指定位置
print(f.tell())   #返回当前光标所在索引位置
print(f.readable()) #文件是否可读,返回布尔值
print(f.readline()) #读一行内容
print(f.readlines(4))   #读取所有内容,并每行内容会加入list中

9.编码与解码

#编码与解码
# str ----------> bytes
a = '尘缘'.encode('utf-8')    #encode编码
print(a)

# bytes --------> str
b = a.decode('utf-8')       #decode解码
print(b)

 

posted @ 2017-12-25 20:29  一拳法师  阅读(303)  评论(0编辑  收藏  举报