码迷,mamicode.com
首页 > 编程语言 > 详细

Python file 文件读写

时间:2019-10-11 20:08:49      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:读文件   需要   文件编码   lin   readlines   end   nes   读写   字节   

需要自己创建好 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

 

Python file 文件读写

标签:读文件   需要   文件编码   lin   readlines   end   nes   读写   字节   

原文地址:https://www.cnblogs.com/bfme/p/11656128.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!