栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python文件

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python文件

编码,常用的有ASCII,unicode,utf-8等

>>> st='东风冷雪'
>>> st
'东风冷雪'
>>> st1=st.encode("utf-8")
>>> st1
b'xe4xb8x9cxe9xa3x8exe5x86xb7xe9x9bxaa'
>>> st1.decode("utf-8")
'东风冷雪'

文本文件 是基于字符编码的文件,常见的有ASCII,和Unicode编码等,其文件的内容就是字符。

二进制文件是基于值编码的文件,存储的是二进制数据,就是数据是按照其占用的字节数来存放的。

文件的打开与关闭
文件对象=open(filename,modern);
文件对象.close();

r只读方式打开;
w以写的方式打开,若文件存在,则覆盖原来的文件
a以写的方式打开,写入内容追加在文章末尾。

import os
os.chdir("D:\")
f=open("test.txt",'rb+')
print(f.read().decode("utf-8"))
f.close()
hello 东风冷雪
life is short.
i use python

定位
通过open语句创建了一个文件对象,读写指针会定位在文件头部,即最左边开始的位置,然后从左到右循序访问。

seek(偏移值,起始位置)函数,可以实现文件随意读写。
起始位置:0文件开始,1当前文件指针,2 文件末尾

import os
os.chdir("E:\")
f=open("test.txt",'w+')
print(f.read())
f.write(" 人生苦短,我用python")
f.seek(1)
print(f.read())
f.close()   
人生苦短,我用python

文件的读,取,追加。
f.read(size)
返回一个字符串,为size长度,如果省略,则是整个文本。

import os
f=open("E:\test.txt",'r+')
str=f.read()
print("f={0},str={1}".format(f,str))
f=<_io.TextIOWrapper name='E:\test.txt' mode='r+' encoding='cp936'>,str=好好学习,天天向上。
good good study。
day day up。
import os
f=open("E:\test.txt",'r+')
str=f.read()
print(str)
str1=f.read()
print("str1=",str1)
f.seek(0)
str2=f.read(1)
print("str1=",str2)
f.close()
好好学习,天天向上。
good good study。
day day up。
str1= 
str1= 好

f.readline()方法 ,返回一个字符串,为当前的一行。换行符字符串末尾。 如果达到末尾则还回一个空字符串,如果是一个空行,返回'n'

import os
f=open("E:\test.txt",'r+')
str1=f.readline()
print("str1=",str1)
str2=f.readline()
print("str2=",str2)
f.close()
str1= 好好学习,天天向上。
str2= good good study。

利用: 如果达到末尾则还回一个空字符串,循环读取,文件内容。

import os
f=open("E:\test.txt",'r+')
line=f.readline()
while  line !="":
    print(line)
    line=f.readline()
f.close()
好好学习,天天向上。
good good study。
day day up。

f.readlines()方法,返回一个列表,列表的每一个字符串元素对应文件的每行。

import os
f=open("E:\test.txt",'r+')
lt=f.readlines()
print(lt)
print("-------------")
for fl in range(len(lt)):
    print(lt[fl])
f.close()   
['好好学习,天天向上。n', 'good good study。n', 'day day up。']
-------------
好好学习,天天向上。
good good study。
day day up。

将一个文件数据写入列表
list=list(open(filename))

>>> lt=list(open("E:\test.txt",'r+'))
>>> lt
['好好学习,天天向上。n', 'good good study。n', 'day day up。']
>>> len(lt)
3

还有许多细节,省略了。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/225220.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号