文件的操作

操作文件时,一般需要经历如下步骤:

打开文件
操作文件

 

一、打开文件:

1 文件句柄 = file('文件路径', '模式')

注:python中打开文件有两种方式,即:open(...) 和  file(...) ,本质上前者在内部会调用后者来进行文件操作,推荐使用 open

打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

打开文件的模式有:

  • 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、读写文件:
f = open('db','r')     #只读
f = open('db','w')   #只写,先清空原文件
f = open('db','x')   #如果文件存在,报错,如果不存在,创建并写内容
f = open('db','a')   #追加
 1 #####只读#####
 2 
 3 #正好只读方式打开(不包含“b”)
 4 f = open('yesterday','r',encoding='utf-8')
 5 data = f.read()
 6 print(data,type(data))
 7 f.close()
 8 
 9 #以二进制的方式读取:(包含“b”)
10 f = open("yesterday",'rb')
11 data = f.read()
12 print(data,type(data))
13 
14 
15 
16 #####追加#####
17 
18 #二进制的方式追加写入(包含“b”)
19 #二进制写入的时候无需python进行转换,但需要指定存入的字符集
20 f = open("yesterday",'ab')
21 f.write(bytes("李杰",encoding="utf-8"))
22 f.close()
23 
24 #字符串追加写入(不包含“b”)
25 f = open("yesterday",'a')
26 f.write("李杰")
27 f.close()
28 
29 
30 
31 ############读写##############
32 #先读,然后在写
33 f = open("yesterday",'r+',encoding="utf-8")
34 data = f.read(1)
35 print(data)
36 f.write("777".strip())
37 f.close()
38 
39 
40 ###########指定位置读写############
41 #读指定位置,进行写入:(覆盖指针后对应的字符)
42 f = open("yesterday",'r+',encoding="utf-8")
43 data = f.read(1)   #如果是r+b的方式打开read()读取的是一个字节,否则是一个字符
44 print(data)
45 f.seek(1)         #永远是以字节的方式找位置
46 f.write("777".strip())
47 f.close()
48 
49 
50 
51 #################在光标指定的位置进行插入##################
52 
53 f = open("yesterday",'r+',encoding="utf-8")
54 data = f.read(1)  #如果打开模式无b,则read,会按照字符读取
55 print(f.tell())   #tell当前指针所在的位置(字节)
56 f.seek(f.tell())  #调整到tell返回的指针的位置(字节)
57 f.write("888")    #当前指针位置开始覆盖
58 f.close()
59 
60 
61 #a+:读写,每次写入都在最后开始追加
62 #w+:读写,每次写入都会先清空原数据在写入
 
总结:
1、read() #无参数,读全部。有参数:
                                                         有b: 按字节
                                                         无b:按字符
2、tell():获取当前指针位置(字节)
3、seek():指针跳转到指定位置(字节)
4、write():写数据,与打开方式有关系:
                                                         有b: 按字节
                                                         无b:按字符
5、fileno:检测文件是否发生变化。
6、flush():强制刷新。
###############强制刷新###################
f = open("yesterday",'a',encoding="utf-8")
f.write("aaaaaaaaaaa")
input("asdfghjkl:")
f.flush()

f = open("yesterday",'r',encoding="utf-8")
print(f.read())
7、readline():仅读取一行,一次只读取一行
8、truncate():截断,指针位置后面全部清空。
1 ################截断指针位置后面的被清空################
2 f = open("yesterday",'r+',encoding="utf-8")
3 f.seek(3)
4 f.truncate()
5 f.close()

9、打开一个文件,通过循环这个对象的时候,会一行一行的迭代这个文件句柄:

#####################for循环文件对象#########################
#注意:防止大文件冲刷内存
f = open("yesterday",'r+',encoding="utf-8")
for line in f:
    print(line)

 

三、关闭文件
通过close关闭:
f.close()

 

三、使用with进行操作:

特点:

1、with可以同时打开2个文件进行操作:
2、with执行完后代码块会自动个关闭无需,f.close():

 1 ##################一个文件读,一个文件写####################
 2 #用途:1、备份某个文件;2、在某个文件中间添加数据;3、提取文件某行记录
 3 with open("yesterday",'r',encoding="utf-8") as f,open("yesterday2",'w',encoding="utf-8") as f1:
 4     count = 0
 5     for line in f:
 6 
 7         print(line)
 8         if count <= 9:
 9             f1.write(line)
10             count += 1
11         else:
12             break
13 
14 
15 
16 ####################文件备份################################
17 #f1文件替换数据并导入到f2文件
18 with open("yesterday",'r',encoding="utf-8") as f1,open("yesterday2",'w',encoding="utf-8") as f2:
19     for line in f1:
20         new_str = line.replace("","Abiao")
21         f2.write(new_str)
22 
23 with open("yesterday2",'r',encoding="utf-8") as f3:
24     for line in f3:
25         print(line.strip('\n'))
26 
27 
28 ######################加入判断的文件备份###############################
29 
30 with open("yesterday",'r',encoding="utf-8") as f1,open("yesterday2",'w',encoding="utf-8") as f2:
31     for line in f1:
32         if "" in line:
33             new_str = line.replace("","alex")
34             f2.write(new_str)
35 
36 with open("yesterday2",'r',encoding="utf-8") as f3:
37     for line in f3:
38         print(line)

 

四、文件操作的源代码:

  1 class file(object):
  2   
  3     def close(self): # real signature unknown; restored from __doc__
  4         关闭文件
  5         """
  6         close() -> None or (perhaps) an integer.  Close the file.
  7          
  8         Sets data attribute .closed to True.  A closed file cannot be used for
  9         further I/O operations.  close() may be called more than once without
 10         error.  Some kinds of file objects (for example, opened by popen())
 11         may return an exit status upon closing.
 12         """
 13  
 14     def fileno(self): # real signature unknown; restored from __doc__
 15         文件描述符  
 16          """
 17         fileno() -> integer "file descriptor".
 18          
 19         This is needed for lower-level file interfaces, such os.read().
 20         """
 21         return 0    
 22  
 23     def flush(self): # real signature unknown; restored from __doc__
 24         刷新文件内部缓冲区
 25         """ flush() -> None.  Flush the internal I/O buffer. """
 26         pass
 27  
 28  
 29     def isatty(self): # real signature unknown; restored from __doc__
 30         判断文件是否是同意tty设备
 31         """ isatty() -> true or false.  True if the file is connected to a tty device. """
 32         return False
 33  
 34  
 35     def next(self): # real signature unknown; restored from __doc__
 36         获取下一行数据,不存在,则报错
 37         """ x.next() -> the next value, or raise StopIteration """
 38         pass
 39  
 40     def read(self, size=None): # real signature unknown; restored from __doc__
 41         读取指定字节数据
 42         """
 43         read([size]) -> read at most size bytes, returned as a string.
 44          
 45         If the size argument is negative or omitted, read until EOF is reached.
 46         Notice that when in non-blocking mode, less data than what was requested
 47         may be returned, even if no size parameter was given.
 48         """
 49         pass
 50  
 51     def readinto(self): # real signature unknown; restored from __doc__
 52         读取到缓冲区,不要用,将被遗弃
 53         """ readinto() -> Undocumented.  Don't use this; it may go away. """
 54         pass
 55  
 56     def readline(self, size=None): # real signature unknown; restored from __doc__
 57         仅读取一行数据
 58         """
 59         readline([size]) -> next line from the file, as a string.
 60          
 61         Retain newline.  A non-negative size argument limits the maximum
 62         number of bytes to return (an incomplete line may be returned then).
 63         Return an empty string at EOF.
 64         """
 65         pass
 66  
 67     def readlines(self, size=None): # real signature unknown; restored from __doc__
 68         读取所有数据,并根据换行保存值列表
 69         """
 70         readlines([size]) -> list of strings, each a line from the file.
 71          
 72         Call readline() repeatedly and return a list of the lines so read.
 73         The optional size argument, if given, is an approximate bound on the
 74         total number of bytes in the lines returned.
 75         """
 76         return []
 77  
 78     def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
 79         指定文件中指针位置
 80         """
 81         seek(offset[, whence]) -> None.  Move to new file position.
 82          
 83         Argument offset is a byte count.  Optional argument whence defaults to
 84         0 (offset from start of file, offset should be >= 0); other values are 1
 85         (move relative to current position, positive or negative), and 2 (move
 86         relative to end of file, usually negative, although many platforms allow
 87         seeking beyond the end of a file).  If the file is opened in text mode,
 88         only offsets returned by tell() are legal.  Use of other offsets causes
 89         undefined behavior.
 90         Note that not all file objects are seekable.
 91         """
 92         pass
 93  
 94     def tell(self): # real signature unknown; restored from __doc__
 95         获取当前指针位置
 96         """ tell() -> current file position, an integer (may be a long integer). """
 97         pass
 98  
 99     def truncate(self, size=None): # real signature unknown; restored from __doc__
100         截断数据,仅保留指定之前数据
101         """
102         truncate([size]) -> None.  Truncate the file to at most size bytes.
103          
104         Size defaults to the current file position, as returned by tell().
105         """
106         pass
107  
108     def write(self, p_str): # real signature unknown; restored from __doc__
109         写内容
110         """
111         write(str) -> None.  Write string str to file.
112          
113         Note that due to buffering, flush() or close() may be needed before
114         the file on disk reflects the data written.
115         """
116         pass
117  
118     def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
119         将一个字符串列表写入文件
120         """
121         writelines(sequence_of_strings) -> None.  Write the strings to the file.
122          
123         Note that newlines are not added.  The sequence can be any iterable object
124         producing strings. This is equivalent to calling write() for each string.
125         """
126         pass
127  
128     def xreadlines(self): # real signature unknown; restored from __doc__
129         可用于逐行读取文件,非全部
130         """
131         xreadlines() -> returns self.
132          
133         For backward compatibility. File objects now include the performance
134         optimizations previously implemented in the xreadlines module.
135         """
136         pass
View Code

 

 

五、不推荐使用的参数:

**************************************以下函数不推荐使用***********************************************

#以list的方式显示文件句柄:(读小文件)
注意:将整个文件读取到内存中,因此只能读小文件
f = open("yesterday",'r',encoding="utf-8")
print(f.readlines())


#加载整个文件数据到内存,以list方式循环句柄:
for line in f.readlines():
    print(line.strip())   #并去掉换行和首尾空格


#打印文本句柄,在第5行的时候显示分割线:
#比较 low的循环,因为在大文件读取的时候会直接把数据一次性加载到内存,会导致内存撑爆。
#放弃这种方式:
f = open("yesterday",'r',encoding="utf-8")
for index,line in enumerate(f.readlines()):
    if index == 4:
        print("---------------分割线------------------")
        continue
    print(line.strip())

**************************************以上函数不推荐使用***********************************************

 

六、文件操作常用的参数:
1、写入、创建、并覆盖原文件内容:(w:写入并创建,覆盖原本内容。)
1 f = data = open("yesterday2",'w',encoding="utf-8") #文件句柄:文件变量 = (包含:文件名、打开文件的模式、字符集、大小、内存的起始位置)
2 f_w = f.write("我爱北京天安门 \n")
3 f_w = f.write("天安门上太阳升 \n")
4 f.close()

 

2、追加文件内容:(a:)

1 f = open("yesterday2",'a',encoding="utf-8") #文件句柄:文件变量 = (包含:文件名、打开文件的模式、字符集、大小、内存的起始位置)
2 f.write("\nwhen i was young i listen to the redio\n")
3 r_f = f.read()
4 print(r_f)
5 f.close()

 

3、读和写追加模式(r+):用处最多
#注意:以r+的方式打开,在写入字符时,是在后面追加

1 f = open("yesterday2",'r+',encoding="utf-8")
2 print(f.readline())
3 print(f.readline())
4 print(f.readline()) #读取三行
5 print(f.tell())     #打印光标
6 f.write("-------diao--------")  #写入字符

 

 

4、写读方式打开(用处不大)

#删除就文件,创建新文件,写入时往后追加
#注意:在2.0的版本里源文件的修改是直接覆盖掉源字符,3.0后只能追加写

 

 1 f = open("yesterday2",'w+',encoding="utf-8")
 2 f.write("-------------diao------------1\n")
 3 f.write("-------------diao------------1\n")
 4 f.write("-------------diao------------1\n")
 5 f.write("-------------diao------------1\n")
 6 f.write("-------------diao------------1\n")
 7 print(f.tell())
 8 f.seek(10)
 9 print(f.tell())
10 print(f.readline())
11 f.write("aaaaaaaaaaaaaaaaaaaaaaaaaa")
12 f.close()

 

 

5、追加读写:

 1 f = open("yesterday2",'a+',encoding="utf-8")
 2 f.write("---------diao-------1\n")
 3 f.write("---------diao-------1\n")
 4 f.write("---------diao-------1\n")
 5 f.write("---------diao-------1\n")
 6 print(f.tell())
 7 f.seek(15)
 8 print(f.tell())
 9 print(f.readline())
10 f.write("bbbbbbbbbbbbbbbbbbbbbb")
11 f.close()

 

6、以二进制格式读取文件句柄:

#以二进制方式读取不需要加字符集
#用途:
#1、网络传输时只能用二进制格式:(2.0里还能用字符,3.0修正)
#2、需要打开二进制文件的时候使用:(二进制文件以字符形式打开会造成文件损坏)

 

1 f = open("yesterday2",'rb')
2 print(f.readline())
3 print(f.readline())

 

 

7、写二进制:

 

#直接写字符是不行的,需要做字符和数字转换:

 

#文件内容不是0101的方式,而是以二进制的方式进行处理
1 f = open("yesterday2",'wb')
2 f.write("hello binary\n".encode(encoding='utf-8'))
3 f.close()
 

 

8、打印光标位置

 

#注意光标到文本最后一行,会在继续读,由于后面的东西没有导致光标无法读出东西。

 

#因此需要将光标移动到一开始的位置。
1 f = open("yesterday",'r',encoding="utf-8")
2 print(f.tell())
3 #print(f.readline())   #有多少个字符就记录多少个数。
4 print(f.read(5))       #read()默认不输入东西,就表示所有,()里的5代表只读5个字符
5 print(f.tell())        #打印光标在哪个位置

 

9、指定光标返回到某个位置。

#读了多行,返回光标。

1 f = open("yesterday",'r',encoding="utf-8")
2 print(f.tell())
3 print(f.readline())  #读三行
4 print(f.readline())
5 print(f.readline())
6 print(f.tell())
7 f.seek(10)            #指定光标退回到那个位置上(前提要知道光标退回的位置)
8 print(f.readline())   #从当前的位置到第一个换行符打印出来

 

10、打印文件的编码:

 1 print(f.encoding) 

 

11、如果能移动光标就返回True,如果不能就返回False

# 不是所有的文件都能移动光标的,有些二进制的文件是无法读取的。

 1 print(f.seekable()) 

 

12、判断文件是否可读:

#如果可读返回True,如果不可读返回为false。

 1 print(f.readable()) 

 

13、判断文件是否可写:

#如果可写返回True,如果不可写返回false。
  1 print(f.writable()) 

 

14、刷新缓存的数据落盘

#在更新数据时,数据时存放在内存中的,防止内存数据丢失,则使用flush()进行刷新
#使用场景:要求数据必须实时的落盘。
1 f = open("yesterday2",'a+',encoding="utf-8")
2 f.write("hello\n")  #写入的数据放在缓存里
3 f.flush()           #刷新缓存落盘
4 f.write("hello2\n")

 

 

15、判断文件是否关闭了:

关闭返回True,没关闭返回False
  1 print(f.closed) 
 
 
16、清空文件内容:
#从第20个字符截断,保存前面字符,去掉后面的
1 f = open("yesterday2",'a+',encoding="utf-8")
2 f.truncate(20)

 

 

转载于:https://www.cnblogs.com/abobo/p/8035695.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值