Python Advanced (30) – File Operations (Part 2)

Original link: https://chegva.com/5477.html

◎Knowledge points

  1. write file

  2. close file

  3. file pointer

◎Script practice

▽ Write file

 """ Before writing to a file, the file must be opened. You can call the built-in function open() and open a file for write-only, append, or read-write. Thus, the returned file object has two methods for writing the file: 1. write(text) Used to write the specified string to a file. After calling, the specified string will be written to the cache first, and the method flush() will be called manually. After or close(), or when the amount of data written is greater than or equal to the capacity of the cache, the string in the cache will be written to the file.  The return value of the method is the number of characters written, that is, the length of the specified string. """  """ >>> file = open('myfile.txt', 'w') >>> file.write('hello') 5 >>> file.write('python') 6 >>> file.flush() >>> file.close()  >>> file = open('myfile.txt', 'a') >>> file.write('hello') 5 >>> file.write('python') 6 >>> file.close() """  """ 2. writelines(seq) Used to sequentially write the specified sequence of strings to the file. After the call, the specified string sequence will be written into the cache first. After manually calling the flush() or close() method, or when the amount of data written is greater than or equal to the cache capacity, the string sequence in the cache will be stored. will be written to the file. """  """ >>> file = open('myfile.txt', 'w') >>> file.writelines(['123\n', '456\n', '789']) >>> file.close() """ 

▽ Close file

 """ The file must be closed after use, because the file object will occupy the resources of the operating system, and the number of files that the operating system can open at a time is also limited. An exception may occur when reading or writing a file, resulting in the method close() not being called. In order to ensure that the method close() can always be called, you can put the operation of reading or writing the file in the try block, and put the call of the method close() in the finally clause. The pseudo code is as follows: Open the file try: read file or write file finally: Call the method close() to close the file  File objects can act as context managers because they implement the special methods __enter__() and __exit__(). Among them, the special method __enter__() returns the open file object, and the special method __exit__() closes the open file, so, The above pseudocode can be implemented using the with statement: with opens the file as file: Read file or write file"""  file = open('myfile.txt', 'w') try: file.write('hello') finally: file.close()  with open('myfile.txt', 'a') as file: file.write('python') 

File pointer

 """ 1. What is a file pointer? Any file object has a file pointer, which points to a certain position in the file. When reading and writing a file, it starts reading and writing from the current position of the file pointer. During the reading and writing process, the file pointer will move backward.  2. The position of the file pointer after opening the file After opening the file by appending, the file pointer points to the end of the file; after opening the file in other ways, the file pointer points to the beginning of the file. The method tell() of the file object can be called to return the current position of the file pointer. """  with open('myfile.txt', 'r') as file: print(file.tell()) # 0  with open('myfile.txt', 'r') as file: print(file.tell()) # 10  """ 3. The movement process of the file pointer when reading and writing files"""  with open('myfile.txt', 'r') as file: print(file.tell()) # 0  file.read(3) print(file.tell()) #3  file.read(4) print(file.tell()) #7  file.read() print(file.tell()) # 10  with open('myfile.txt', 'a') as file: print(file.tell()) # 10  file.write('hello') print(file.tell()) #15  with open('myfile.txt', 'w') as file: print(file.tell()) # 0  file.write('hello') print(file.tell()) #5  """ 4. Freely move the file pointer The method seek(offset[, whence]) of the file object can be called to freely move the file pointer to the position specified by the parameter, where: The parameter offset represents the offset, which can be negative; the parameter whence is optional and represents the relative offset position. There are three values: (1) os.SEEK_SET: relative to the starting position of the file, the value is 0, the default value (2) os.SEEK_CUR: relative to the current position of the file, the value is 1 (3) os.SEEK_END: ​​relative to the end of the file, the value is 2   For files opened in text mode, only relative to the beginning of the file is supported. """  import os  with open('myfile2.txt', 'rb') as file: print(file.tell()) # 0  # file.seek(3, os.SEEK_SET) # file.seek(3, 0) file.seek(3) print(file.tell()) #3  file.seek(4, os.SEEK_CUR) print(file.tell()) #7  file.seek(-2, os.SEEK_END) print(file.tell()) #8  with open('myfile2.txt', 'r+') as file: print(file.tell()) # 0  file.seek(3) print(file.tell()) #3  file.write('python') print(file.tell()) #9 

读写文件时文件指针的移动过程.png

◎Script address: https://github.com/anzhihe/learning/blob/master/python/practise/learn-python/python_advanced/file_operations2.py

This article is reprinted from: https://chegva.com/5477.html
This site is for inclusion only, and the copyright belongs to the original author.