码迷,mamicode.com
首页 > 编程语言 > 详细

python基础(文件操作)

时间:2017-12-25 20:57:56      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:txt   上传   源文件   用法   pos   字符   nbsp   blog   添加   

文件操作

1,文件路径

绝对路径:从根目录到目标文件路径

#绝对路径
f = open(d:\模特主妇护士班主任.txt,mode=r,encoding=UTF-8)
content = f.read()
print(content)
f.close()

 

相对路径:根目录相同文件夹下的文件名

2,编码方式:utf-8,gbk.......

3,操作方式:只读,只写,追加,读写,写读.....

文件读取:以什么编码方式存储的就以什么编码方式打开

# f = open(‘文件路径‘,mode=‘r‘,encoding=‘UTF-8‘)
# content = f.read()
# print(content)
# f.close()

只读:

  r(Unicode类型)  rb(bytes类型)

              1,非文字类的文件用rd打开

              2,上传 下载 储存文件用rb.

只写:w:没有此文件就会创建文件

#对于w:没有此文件就会创建文件
# f = open(‘log‘,mode=‘w‘,encoding=‘utf-8‘)
# f.write(‘骑兵步兵‘)
# f.close()

有文件,先将源文件的内容全部清除,再写

# 先将源文件的内容全部清除,在写。
# f = open(‘log‘,mode=‘w‘,encoding=‘utf-8‘)
# f.write(‘附近看到类似纠纷‘)
# f.close()

 

wb:

# f = open(‘log‘,mode=‘wb‘)
# f.write(‘附近看到类似纠纷‘.encode(‘utf-8‘))
# f.close()

 w+:

f = open(log,mode=w+,encoding=utf-8)
# f.write(‘aaa‘)
# f.seek(0)
# print(f.read())
# f.close()

 

追加:

a:

# f = open(‘log‘,mode=‘a‘,encoding=‘utf-8‘)
# f.write(‘佳琪‘)
# f.close()

 

ab:

f = open(log,mode=ab)
# f.write(‘佳琪‘.encode(‘utf-8‘))
# f.close()

 

a+:

 f = open(log,mode=a+,encoding=utf-8)
# f.write(‘佳琪‘)
# f.seek(0)
# print(f.read())
# f.close()

 

读写:

r+:

(r+b)bytes类型

# obj = open(‘log‘,mode=‘r+‘,encoding=‘utf-8‘)
# content = f.read(3)  # 读出来的都是字符
# f.seek(3)  # 是按照字节定光标的位置
# f.tell() 告诉你光标的位置
# print(f.tell())
# content = f.read()
# print(content)
# f.tell()
# f.readable()  # 是否刻度
# line = f.readline()  # 一行一行的读
# line = f.readlines()  # 每一行当成列表中的一个元素,添加到list中
# f.truncate(4)
# for line in f:
#     print(line)
# f.close()

 

 

关键用法:

.read()读出来的是字符

.seek()按字节来找光标

.tell()告诉你光标的位置

.readline()一行一行的读

.readlines()每一行当成列表的一个元素添加到列表中

.truncate()截取一段来显示

编码方式:

bytes----->str  decode 解码

str ------>bytes     encode 编码

#str --->byte  encode 编码
# s = ‘二哥‘
# b = s.encode(‘utf-8‘)
# print(b)
# #byte --->str decode 解码
# s1 = b.decode(‘utf-8‘)
# print(s1)

 

python基础(文件操作)

标签:txt   上传   源文件   用法   pos   字符   nbsp   blog   添加   

原文地址:https://www.cnblogs.com/chenshuaiv587/p/8110937.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!