Home  >  Article  >  Backend Development  >  Summary of related content of file operations in python (with examples)

Summary of related content of file operations in python (with examples)

不言
不言forward
2018-10-29 17:37:072542browse

This article brings you a summary of relevant content about file operations in python (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Introduction to file operations

When it comes to operating files, we will definitely think of streams. File operations are all performed through streams. The operation of files in python is very simple. Unlike other languages ​​such as Java, which have various stream operations, we can directly use the open function to open a file and then perform various operations. However, depending on the way of opening, The operations that can be performed are also different. The ways to open files are: r, w, a, r , w , a , rb, wb, ab, r b, w b, a b and so on.

Let’s first look at a read file operation:

In [2]: f = open(file='a.txt', mode='r', encoding='utf-8')

In [3]: f.read()
Out[3]: '每天坚持一点,\n每天努力一点,\n每天多思考一点,\n慢慢你会发现,\n你的进步越来越大\n'
In [4]:

Use the open function to open the file and return a file object. Several common parameters of the open function are file (the name of the file to be operated). ), mode (in what mode to open) and encoding (specify an encoding to read the file), depending on the mode, the returned file will have various operations. Let's take a look at several operations on files.

2. Several ways to operate files

(1) Read-only operation

For read-only operation, just specify mode as r:

In [5]: f = open(file='a.txt', mode='r', encoding='utf-8')
 
In [6]: f.read()
Out[6]: '每天坚持一点,\n每天努力一点,\n每天多思考一点,\n慢慢你会发现,\n你的进步越来越大\n'
 
In [7]: f.readable()                # 判断文件是否可读
Out[7]: True
 
In [8]: f.writable()                # 判断文件是否可写
Out[8]: False                       # 此处是以只读模式打开的文件,所以返回False不可写
 
In [9]: f1 = open(file='单分支结构.eddx', mode='rb')        # 使用‘rb’可以打开存储为二进制的数据,图片、视频等
 
In [10]: f1.read(20)
Out[10]: b'PK\x03\x04\x14\x00\x08\x00\x08\x00mN\xe3H\xa9\x95\xb3\x9eW\x01'

(2) Write-only operation

mode='w'

                                                                             
In [13]: f = open(file='a.txt', mode='w', encoding='utf-8')                  
                                                                             
In [14]: f.read()                       # 此时尝试读取文件会报错                                            
---------------------------------------------------------------------------  
UnsupportedOperation                      Traceback (most recent call last)  
<ipython-input-14-571e9fb02258> in <module>                                  
----> 1 f.read()                                                             
                                                                             
UnsupportedOperation: not readable                                           
                                                                             
In [15]: f.write(&#39;葫芦娃&#39;)                                                      
Out[15]: 3                                                                   
                                                                             
In [16]: f.close()                                                           
                                                                             
In [17]: !cat a.txt                     # 此时查看文件之前那的内容已经被覆盖了                             
葫芦娃                                                                          
In [18]:

When using mode='w' to operate a file, the file will be cleared first when opening the file. Then the content is written to the file according to the operation. The read-only mode has the following characteristics:

  • When the file does not exist, the file will be automatically created, and then the file will be opened for operation

  • When opening a file, the contents of the file will be cleared first, and then written from the beginning

  • The file is opened in write-only mode and cannot be read

(3) Append operation

mode='a'

In [18]: f = open(file=&#39;a.txt&#39;, mode=&#39;a&#39;, encoding=&#39;utf-8&#39;)
 
In [19]: f.write(&#39;每天坚持一点,\n每天努力一点,\n每天多思考一点,\n慢慢你会发现,\n你的进步越来越大\n&#39;)
Out[19]: 42
 
In [20]: f.close()
 
In [21]:
 
In [21]: !cat a.txt
葫芦娃每天坚持一点,
每天努力一点,
每天多思考一点,
慢慢你会发现,
你的进步越来越大
 
In [22]:

Append mode operation:

  • Open the file If the file does not exist, the file will be created first

  • When writing content to the file will always be written at the end of the file, no matter where the cursor is

  • The opened file can only be written, not read

(4)r mode

r The mode is an enhanced read operation, that is, it can read and write:

In [22]: f = open(file=&#39;a.txt&#39;, mode=&#39;r+&#39;, encoding=&#39;utf-8&#39;)

In [23]: f.readable()
Out[23]: True

In [24]: f.writable()
Out[24]: True

In [25]: f.read()
Out[25]: &#39;葫芦娃每天坚持一点,\n每天努力一点,\n每天多思考一点,\n慢慢你会发现,\n你的进步越来越大\n&#39;

In [26]: f.write(&#39;\n哈哈哈哈哈哈哈&#39;)
Out[26]: 8

In [27]: f.close()

In [28]: !cat a.txt         # 查看写入的文件并没有异常
葫芦娃每天坚持一点,
每天努力一点,
每天多思考一点,
慢慢你会发现,
你的进步越来越大

哈哈哈哈哈哈哈
In [29]: f = open(file=&#39;a.txt&#39;, mode=&#39;r+&#39;, encoding=&#39;utf-8&#39;)

In [30]: f.seek(0, 2)       # seek可以调整光标位置
Out[30]: 153

In [31]: f.write(&#39;你的进步越来越大&#39;)
Out[31]: 8

In [32]: f.read()           # 先写后读会读出空字符
Out[32]: &#39;&#39;

In [33]:

Summary: The enhanced read operation can read and write files, but the order must be to read first and then write to it. If you read first and then write When writing and reading, you may read an empty string

r mode. Please note: In r mode. If the content is read, no matter how much content is read, the cursor will be displayed. It shows how much. When writing or operating the file, the operation is performed at the end

(5)w and a mode

w mode and a mode are at There are few actual usage scenarios. Here is a brief introduction:

  • w: Enhanced w mode, which can write and read operations, but it is also the same as r. If you read first and then write There will be pitfalls during operation, and every time a file is opened, the file will be cleared first, so there are fewer usage scenarios

  • a: Enhanced a mode, you can also perform read and write operations , but when writing, it can only be written to the end of the file. No matter how the cursor moves, it can only be written to the end of the file.

3. File operation methods

(1) File reading and writing

File writing: mainly write method and writelines method

  • write method: just write the string directly. The above example also uses

  • writelines method: the parameters passed can be iterated if necessary (such as lists and tuples, etc.)

Reading of files :

  • read method: read method receives An int type parameter, indicating how many characters are read at a time (the unit of seek is bytes). If not provided, the default is to read all the contents of the file

  • readline method: read one line of the file , this method is very useful when the file is very large, and the entire file will not be read at once

  • readlines method: Read the entire file, divide it into a list by each line, and return this List

In [34]: f = open(file=&#39;a.txt&#39;, mode=&#39;r&#39;, encoding=&#39;utf-8&#39;)
# 葫芦娃每天坚持一点,
# 每天努力一点,
# 每天多思考一点,
# 慢慢你会发现,
# 你的进步越来越大
 
# 哈哈哈哈哈哈哈你的进步越来越大
In [35]: f.read(10)                 # 这里时一次读取10个字符
Out[35]: &#39;葫芦娃每天坚持一点,&#39;
 
In [36]: f.readline()
Out[36]: &#39;\n&#39;
 
In [37]: f.readline()               # 每次读取一行
Out[37]: &#39;每天努力一点,\n&#39;
 
In [38]: f.readlines()              # 返回的是一个列表
Out[38]: [&#39;每天多思考一点,\n&#39;, &#39;慢慢你会发现,\n&#39;, &#39;你的进步越来越大\n&#39;, &#39;\n&#39;, &#39;哈哈哈哈哈哈哈你的进步越来越大&#39;]
 
In [39]:

The difference between readline (file handle) and readlines

The file handle is an iterable object. During loop traversal, one line is taken each time it is traversed, and it will not be When reading a file, read it all at once.

The result returned by readlines is a list. It will read the contents of the entire file at once and return a list. When processing large files, it will consume a lot of resources.

You can also use a loop to traverse the file handle and output the contents of the file:

In [39]: f.seek(0)
Out[39]: 0

In [40]: for line in f:
    ...:     print(line.strip())
葫芦娃每天坚持一点,
每天努力一点,
每天多思考一点,
慢慢你会发现,
你的进步越来越大

哈哈哈哈哈哈哈你的进步越来越大

In [41]:

(2) Other methods of file operation

  • close: Close the file

  • readable: Determine whether the file is readable

  • seek: Move the cursor and receive two data. The first parameter indicates the offset position. (The unit of movement is byte. So if it is the Chinese part of UTF-8, it must be a multiple of 3). The second parameter indicates the offset from that position (0, represents the beginning, 1 represents the current position, 2 represents the end)

  • seekable:判断当前文件的光标是否可移动

  • tell:返回当前光标所在的位置

  • truncate:截断数据(谨慎操作),默认截断光标后所有字符

  • writable:判断文件是否可写

(3)打开文件的另一种方式

在打开一个文件后,要记得在文件使用结束狗使用close方法关闭文件句柄,但有时在中间进行大量的操作后可能会忘了关闭,下面介绍的这种方法可以不用自己手动关闭文件了,他会在您操作解说后(代码块的语句执行完毕)自动关闭文件句柄,这种方法就是使用context上下文管理,使用with语句实现:

In [43]: with open(&#39;a.txt&#39;, mode=&#39;r&#39;, encoding=&#39;utf-8&#39;) as f:   # 使用with管理上下文,最后退出时会自己执行close动作
    ...:     for line in f:
    ...:         print(line.strip())
葫芦娃每天坚持一点,
每天努力一点,
每天多思考一点,
慢慢你会发现,
你的进步越来越大
哈哈哈哈哈哈哈你的进步越来越大

The above is the detailed content of Summary of related content of file operations in python (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete