【python】文件读写操作

admin 2022年1月10日03:31:45评论30 views字数 1812阅读6分2秒阅读模式

文件读取

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
34
'''
1. 打开文件
2. 操作文件
3. 关闭文件
r #文件不存在则不可读(报错)
w
a
'''
f = open('test.txt','r',encoding='utf8')
# print(f.readable()) #判断文件是否可读

# print(f.read(14)) # 默认 读取全部 \n 换行符都只占一个字节
# print(f.read(14)) # 默认 读取全部 \n 换行符都只占一个字节

# print(f.readline(),end='')
# print(f.readline(),end='')
# print(f.tell())
# print(f.readline(),end='')
# print(f.tell()) #汉字3个字节 字符1个字节 换行符2个字节

# print(f.readlines()[3]) # 读取全部,返回的是列表

# print(f.readlines(19)) # 根据光标来确定数值

'''
第二行添加hello world
'''
res = f.readlines()
for i in range(len(res)):
# print(res[i])
if i == 1 :
print(res[i].strip(),'hello world')
else:
print(res[i])

文件写入

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
'''
模式与方法要匹配
w--》文件不存在 创建文件
'''
# f = open('test1.txt' , 'w')
# # print(f.writable()) # bool
#
# # f.write('hello world') # 覆盖文件
# f.writelines(['hello world\n','hello world'])

'''
a 文件不存在时,创建文件 追加 append
'''
f = open('test2.txt' , 'a')
f.write('hello world \n')

'''
图片
音频
二进制
'''
b = b'hello world'
# print(type(b)) #bytes
f = open('test.txt','wb')
f.write(b) # w 对文本只能写str

'''
json.dumps() -->语句
json.dump() -->文件
'''
import json
# data = {"name":"amy"}
# res = json.dumps(data)
# print(res)
# print(type(res))
# # print(type(data))
# f = open('test.json','w') #dict -->> '{"name":"amy"}'
# json.dump(data,f)

# f = open('test.json','r')
# # print(type(f.read())) # '{"data":{"name":{}}}'
# d_data = json.load(f)
# print(d_data['name'])
# print(type(d_data))

'''
f.close()-->关闭文件
'''
# import time
# f = open('test6.txt','w')
# f.write("hello world")
# time.sleep(5) #程序执行完毕才写入
# f.close()

# try:
# f = open('test6.txt','w')
# f.read()
# except Exception as e:
# print(e)
# finally:
# if f:
# f.close()

'''
上下文管理器
with 自动调用__enter__(), 将方法的返回值给as后面的变量
相当于 f = open()
with后面的代码块全部执行完毕之后,将调用前面返回对象__exit__() --> f.close()
'''
with open('test8.txt','w') as f:
f.write('hello world')

'''
唯一的区别是,with open()自动关闭
open()需要自己f.close()
'''

FROM:gylq.gitee Author:孤桜懶契

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2022年1月10日03:31:45
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   【python】文件读写操作http://cn-sec.com/archives/729966.html

发表评论

匿名网友 填写信息