In the process of computer application, Python file management is easier than other computer languages. If you want to know how Python File Management applies certain modules to file operations, you can watch our articles and hope you can get relevant knowledge from them.
Introduction
The games you 've played use files to save archives; the orders you place are stored in files; obviously, the reports you write in the morning are also saved in files.
File Management is an important part of almost all applications written in any language. Python files are no exception. In this article, we will explore how to use some modules to operate files. We will complete the operations of reading, writing, and adding the file content. There are also some alternative usage.
Read/write files
Of course, the most basic file operation is to read and write data in the file. This is easy to grasp. Open a file to perform the write operation:
- view plaincopy to clipboardprint?
- fileHandle = open ( 'test.txt', 'w' )
FileHandle = open ('test.txt ', 'w') 'W' indicates that the file will be written into data, and other parts of the statement are well understood. The next step is to write data to a file:
- view plaincopy to clipboardprint?
- fileHandle.write ( 'This is a test.\nReally, it is.' )
- fileHandle.write ( 'This is a test.\nReally, it is.' )
This statement writes "This is a test." to the first line of the file, "Really, it is." to the second line of the file. Finally, we need to clean up and disable Python file management:
- view plaincopy to clipboardprint?
- fileHandle.close()
FileHandle. close () as you can see, in Python's object-oriented mechanism, this is indeed very simple. It should be noted that when you use the "w" method to write data in the file again, all the original content will be deleted. If you want to retain the original content, you can use the "a" method to append data to the end of the file:
- view plaincopy to clipboardprint?
- fileHandle = open ( 'test.txt', 'a' )
- fileHandle.write ( '\n\nBottom line.' )
- fileHandle.close()
- fileHandle = open ( 'test.txt', 'a' )
- fileHandle.write ( '\n\nBottom line.' )
- fileHandle.close()
Read/write files
- view plaincopy to clipboardprint?
- fileHandle = open ( 'test.txt' )
- print fileHandle.read()
- fileHandle.close()
- fileHandle = open ( 'test.txt' )
- print fileHandle.read()
- fileHandle.close()
The preceding statement reads the entire file and displays its data. We can also read a row in Python file management:
- view plaincopy to clipboardprint?
- fileHandle = open ( 'test.txt' )
- print fileHandle.rehttp://new.51cto.com/wuyou/adline()
- # "This is a test."
- fileHandle.close()
- fileHandle = open ( 'test.txt' )
- print fileHandle.readline() # "This is a test."
- fileHandle.close()
The above is an introduction to Python file management, and I hope you will find some gains.