Home >Backend Development >Python Tutorial >Detailed explanation of Python file management examples
The example in this article describes the method of Python file management. Share it with everyone for your reference, the details are as follows:
1. File management in Python
File management is a basic function and important component of many applications. Python can make file management extremely simple, especially compared to other languages.
Below, Peyton McCullough explains the basics of file management.
Introduction
The games you played use files to save archives; the orders you placed were saved in files; obviously, the report you wrote that morning was also saved in files.
File management is an important part of the many applications written in almost any language. Python is certainly no exception. In this article, we will explore how to use some modules to manipulate files. We will complete the operations of reading files, writing files, adding file contents, and some alternative usages. OK, let's get started.
Reading and writing files
The most basic file operation is of course reading and writing data in the file. This is also very easy to master. Now open a file for writing:
fileHandle = open ( 'test.txt', 'w' )
'w' means that the file will be written with data, the rest of the statement is easy to understand. The next step is to write the data to the file:
fileHandle.write ( 'This is a test.\nReally, it is.' )
This statement writes "This is a test." to the first line of the file, and "Really, it is." to the second line of the file. Finally, we need to clean up and close the file:
fileHandle.close()
As you can see, this is really simple under Python's object-oriented mechanism. 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 keep the original content, you can use the "a" method to append data to the end of the file:
fileHandle = open ( 'test.txt', 'a' ) fileHandle.write ( '\n\nBottom line.' ) fileHandle.close()
Then, we read test.txt and display the content:
fileHandle = open ( 'test.txt' ) print fileHandle.read() fileHandle.close()
The above statement will read the entire file and display the data in it. We can also read a line in the file:
fileHandle = open ( 'test.txt' ) print fileHandle.readline() # "This is a test." fileHandle.close()
At the same time, we can also save the file content to a list:
fileHandle = open ( 'test.txt' ) fileList = fileHandle.readlines()<DIV></DIV> for fileLine in fileList: print '>>', fileLine fileHandle.close()
Python When reading a file, its position in the file is remembered, as shown below:
fileHandle = open ( 'test.txt' ) garbage = fileHandle.readline() fileHandle.readline() # "Really, it is."fileHandle.close()
As you can see, only the second line is displayed. However, we can solve this problem by asking Python to read from the beginning:
fileHandle = open ( 'test.txt' ) garbage = fileHandle.readline() fileHandle.seek ( 0 ) print fileHandle.readline() # "This is a test." fileHandle.close()
In the above example, we ask Python to start reading data from the first byte of the file. So, the first line of text is displayed. Of course, we can also get the location of Python in the file:
fileHandle = open ( 'test.txt' ) print fileHandle.readline() # "This is a test." print fileHandle.tell() # "17" print fileHandle.readline() # "Really, it is."
or read a few bytes at a time in the file:
fileHandle = open ( 'test.txt' ) print fileHandle.read ( 1 ) # "T" fileHandle.seek ( 4 ) print FileHandle.read ( 1 ) # " "(原文有错)
In Windows and Macintosh environments, sometimes you may need to read and write files in binary mode, such as pictures and executable files. At this time, just add a "b" to the method parameter of opening the file:
fileHandle = open ( 'testBinary.txt', 'wb' ) fileHandle.write ( 'There is no spoon.' ) fileHandle.close() fileHandle = open ( 'testBinary.txt', 'rb' ) print fileHandle.read() fileHandle.close()
2. Obtain information from existing files
Use Python Module that can obtain information from existing files. Use the "os" module and the "stat" module to obtain basic information about the file:
import os import stat import time<DIV></DIV> fileStats = os.stat ( 'test.txt' ) fileInfo = { 'Size' : fileStats [ stat.ST_SIZE ], 'LastModified' : time.ctime ( fileStats [ stat.ST_MTIME ] ), 'LastAccessed' : time.ctime ( fileStats [ stat.ST_ATIME ] ), 'CreationTime' : time.ctime ( fileStats [ stat.ST_CTIME ] ), 'Mode' : fileStats [ stat.ST_MODE ] } for infoField, infoValue in fileInfo: print infoField, ':' + infoValue if stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ): print 'Directory. ' else: print 'Non-directory.'
The above example creates a dictionary containing basic information about the file. Then the relevant information is displayed and tells us whether the opened directory is a directory. We can also try to see if there are other types opened:
import os import stat fileStats = os.stat ( 'test.txt' ) fileMode = fileStats [ stat.ST_MODE ] if stat.S_ISREG ( fileStats [ stat.ST_MODE ] ): print 'Regular file.' elif stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ): print 'Directory.' elif stat.S_ISLNK ( fileStats [ stat.ST_MODE ] ): print 'Shortcut.' elif stat.S_ISSOCK ( fileStats [ stat.ST_MODE ] ): print 'Socket.' elif stat.S_ISFIFO ( fileStats [ stat.ST_MODE ] ): print 'Named pipe.' elif stat.S_ISBLK ( fileStats [ stat.ST_MODE ] ): print 'Block special device.' elif stat.S_ISCHR ( fileStats [ stat.ST_MODE ] ):
In addition, we can use "os.path" to get basic information:
import os.path fileStats = 'test.txt' if os.path.isdir ( fileStats ): print 'Directory.' elif os.path.isfile ( fileStats ): print 'File.' elif os.path.islink ( fileStats ): print 'Shortcut.' elif os.path.ismount ( fileStats ): print 'Mount point.' import os for fileName in os.listdir ( '/' ): print fileName
As you can see, this is simple and can be done in three lines of code.
Creating a directory is also very simple:
import os os.mkdir ( 'testDirectory' )
Delete the directory just created:
import os os.rmdir ( 'testDirectory )
You can also create multi-level directories :
import os os.makedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' ) os.makedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )
If you didn't add anything to the folders you created, you can delete them all at once (i.e. delete all empty folders listed):
import os os.removedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes'
When we need to operate on a specific file type, we can choose the "fnmatch" module. The following is the content of the ".txt" file and the file name of the ".exe" file:
import fnmatch import os for fileName in os.listdir ( '/' ): if fnmatch.fnmath ( fileName, '*.txt' ): print open ( fileName ).read() elif fnmatch.fnmatch ( fileName, '*.exe' ): print fileName
characters can represent any length of characters. If you want to match a character, use the "?" symbol:
import fnmatch import os for fileName in os.listdir ( '/' ): if fnmatch.fnmatch ( fileName, '?.txt' ): print 'Text file.'
The "fnmatch" module supports regular expressions:
import fnmatch import os import re filePattern = fnmatch.translate ( '*.txt' ) for fileName in os.listdir ( '/' ): if re.match ( filePattern, fileName ): print 'Text file.'
If only If you need to match a type of file, a better way is to use the "glob" module. The format of this module is similar to "fnmatch":
import glob for fileName in glob.glob ( '*.txt' ): print 'Text file.'
It is also possible to match a range of characters, just like in a regular expression. Suppose you want to display the file name of a file with only one digit before the extension:
import glob for fileName in glob.glob ( '[0-9].txt' ): print filename
The "glob" module uses the "fnmatch" module to achieve this.
4. Data marshalling
Using the module introduced in the previous section, you can read and write strings in files.
However, sometimes, you may need to pass other types of data, such as list, tuple, dictionary and other objects. In Python you can do it using Pickling. You can accomplish data marshalling using the "pickle" module in the Python standard library.
Next, let’s group a list containing strings and numbers:
import pickle fileHandle = open ( 'pickleFile.txt', 'w' ) testList = [ 'This', 2, 'is', 1, 'a', 0, 'test.' ] pickle.dump ( testList, fileHandle ) fileHandle.close()
It’s also not difficult to split the group:
import pickle fileHandle = open ( 'pickleFile.txt' ) testList = pickle.load ( fileHandle ) fileHandle.close()
Now try to store more complex data:
import pickle fileHandle = open ( 'pickleFile.txt', 'w' ) testList = [ 123, { 'Calories' : 190 }, 'Mr. Anderson', [ 1, 2, 7 ] ] pickle.dump ( testList, fileHandle ) fileHandle.close() import pickle fileHandle = open ( 'pickleFile.txt' ) testList = pickle.load ( fileHandle ) fileHandle.close()
如上所述,使用Python的"pickle"模块编组确实很简单。众多对象可以通过它来存储到文件中。如果可以的话,"cPickle"同样胜任这个工作。它和"pickle"模块一样,但是速度更快:
import cPickle fileHandle = open ( 'pickleFile.txt', 'w' ) cPickle.dump ( 1776, fileHandle ) fileHandle.close()
五、创建"虚拟"文件
你用到的许多模块包含需要文件对象作为参数的方法。但是,有时创建并使用一个真实的文件并让人感到有些麻烦。所幸的是,在Python中,你可以使用"StringIO"模块来创建文件并将其保存在内存中:
import StringIO fileHandle = StringIO.StringIO ( "Let freedom ring" ) print fileHandle.read() # "Let freedom ring." fileHandle.close()
cStringIO"模块同样有效。它的使用方法和"StringIO"一样,但就像"cPickle"之于"pickle",它速度更快:
import cStringIO fileHandle = cStringIO.cStringIO ( "To Kill a Mockingbird" ) print fileHandle.read() # "To Kill a Mockingbid" fileHandle.close()
结论
文件管理,是众多编程语言的程序员在编写应用程序是经常遇到的问题。幸好,和其它语言相比,Python使其出乎意料地容易。Python的标准库中提供了许多相关的模块帮助程序员解决这方面的问题,而它的面向对象的机制也简化了操作。
好了,现在你已经了解了Python中文件管理的基本知识,可以在今后的应用程序中很好地使用了。
希望本文所述对大家Python程序设计有所帮助。
更多Python 文件管理实例详解相关文章请关注PHP中文网!