脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python对文件操作知识汇总

Python对文件操作知识汇总

2020-08-23 11:59张瑞东 Python

这篇文章主要介绍了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

?
1
2
3
4
5
6
7
8
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对象

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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文件操作知识汇总的相关知识,希望对大家有所帮助!

延伸 · 阅读

精彩推荐