python对文件操作知识汇总

打开文件

操作文件

1打开文件时,需要指定文件路径和打开方式

打开方式:

r:只读
w:只写
a:追加

“+”表示可以同时读写某个文件

r+:读写
w+:写读
a+:同a

u”表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)

ru
r+u

“b”表示处理二进制文件(如:ftp发送上传iso镜像文件,linux可忽略,windows处理二进制文件时需标注)

rb
wb
ab

f = open(‘test.log’,’r+’,encoding=’utf-‘)
f.write(‘saf中sdhgrbfds’)
print(f.tell()) #查看当前指针位置,以字符为单位
f.seek() #指定当前指针位置,以字节为单位
print(f.read())
f.truncate() #读取指针之前的数据
print(f.tell())
f.close()

二:常见的文件运算

f = open(‘data’, ‘r’) #以只读形式打开(默认就是只读)
f = open(‘f.txt’, encoding=’latin-1′) #python3.0 unicode文件
string = f.read() #把文件读入一个字符串中
string = f.read(n) #读取指针后的n个字节
string = f.readline() #读取下一行,包括行末标识符
alist = f.readlines() #读取整个文件到字符串列表
f.write() #将字符串写入文件
f.writelines() #将列表内所有字符串写入文件
f.close() #手动关闭
f.flush() #把输出缓冲区刷到硬盘中
f.seek(n) #将文件指针移到n处,以字节为单位
for line in open(‘data’):
print(line) #文件迭代器将文件一行行读出
open(‘f.txt’,’r’).read() #read all at ance into string

三:在文件中存储并解析python对象

x,y,z = 41,42,43
s = ‘spam’
d = {‘a’:1, ‘b’:2} #字典对象
l = [‘a’,’b’,’c’] #列表
f = open(‘f.txt’,’w’)
f.write(s + ‘\n’)
f.write(‘%s,%s,%s\n’%(x,y,z))
f.write(str(d))
f.write(‘\n’)
f.write(str(l))
f.close()
print(open(‘f.txt’).read()) #将文件内容输出
#从文件中取出数据,并判断其类型
”’
a = fi.readline()
b = fi.readline()
c = fi.readline()
d = fi.readline()
print(a,b,c,d,type(a),type(b),type(c),type(d))
”’
# 从文件中取出数据,并转换为存储前的类型
fi = open(‘f.txt’)
a = fi.readline().rstrip() #rstrip()去掉换行符
print(a,type(a))
b = fi.readline().rstrip().split(‘,’) #字符串的split()方法,在括号中写入分隔符,将字符串分割为列表。
print(b,type(b))
c = fi.readline()
c = eval(c) #调用内置函数eval(),将字符串转化为可执行的python代码。
print(c,type(c),type(c))
d = fi.readline()
d = eval(d)
print(d,type(d),type(d))

以上所述是小编给大家介绍的python对文件操作知识汇总的相关知识,希望对大家有所帮助!

Posted in 未分类

发表评论