加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python file 文件读写

发布时间:2020-12-20 10:20:43 所属栏目:Python 来源:网络整理
导读:需要自己创建好 test_file 文件及内容。 ? 1 # !/usr/bin/env python3 2 # -*- coding: utf-8 -*- 3 4 ‘‘‘ 5 #写是重新生成一个新的文件,如果用同名文件会将原来的文件内容清空,请注意 6 file = open(‘test_file‘,mode=‘w‘,encoding=‘utf-8‘) 7 f

需要自己创建好 test_file 文件及内容。

?

 1 #!/usr/bin/env python3
 2 # -*- coding: utf-8 -*-
 3 
 4 ‘‘‘
 5 #写是重新生成一个新的文件,如果用同名文件会将原来的文件内容清空,请注意
 6 file = open(‘test_file‘,mode=‘w‘,encoding=‘utf-8‘)
 7 file.write("ceshi neirong")
 8 file.close()
 9 
10 #追加内容 a 是append的简写
11 file = open(‘test_file‘,mode=‘a‘,encoding=‘utf-8‘)
12 file.write("nceshi neirong 2222222")
13 file.close()
14 
15 file = open(‘test_file‘,mode=‘r+‘,encoding=‘utf-8‘)           #读写,先读取再写入
16 file = open(‘test_file‘,mode=‘w+‘,encoding=‘utf-8‘)           #读写,先写入再读取
17 file = open(‘test_file‘,mode=‘a+‘,encoding=‘utf-8‘)           #追加读
18 
19 file = open(‘test_file‘,mode=‘rb‘,encoding=‘utf-8‘)           #二进制文件读
20 file = open(‘test_file‘,mode=‘wb‘,encoding=‘utf-8‘)           #二进制文件写
21 
22 ‘‘‘
23 
24 
25 #只读文件内容
26 file = open(test_file,mode=r,encoding=utf-8)
27 #print(file.read())
28 
29 
30 print(file.read(1))                         #读取第1个字节,留空则表示全部内容
31 print(file.readlines(1))                    #读取第1行内容,留空则表示一行
32 print("".center(50,"-"))
33 
34 print(file.seek(0))                 #跳到字节的哪一个位置
35 print(file.tell())                  #显示字节当前位置
36 
37 print(file.encoding)                #查询文件编码格式
38 
39 file.flush()     #实时将内容刷新到硬盘上!!!
40 
41 
42 
43 #查询前10行
44 count = 0
45 for line in file:
46     if count == 10 :
47         print("".center(40,*))
48         count +=1
49         continue
50     print(line.strip())
51     count +=1

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读