Home > Backend Development > Python Tutorial > Detailed explanation of Python file management examples

Detailed explanation of Python file management examples

高洛峰
Release: 2017-01-21 14:36:34
Original
1626 people have browsed it

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' )
Copy after login

'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.' )
Copy after login

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()
Copy after login

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()
Copy after login

Then, we read test.txt and display the content:

fileHandle = open ( 'test.txt' ) 
print fileHandle.read() 
fileHandle.close()
Copy after login

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()
Copy after login

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 &#39;>>&#39;, fileLine 
fileHandle.close()
Copy after login

Python When reading a file, its position in the file is remembered, as shown below:

fileHandle = open ( &#39;test.txt&#39; ) 
garbage = fileHandle.readline() 
fileHandle.readline() # "Really, it is."fileHandle.close()
Copy after login

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 ( &#39;test.txt&#39; ) 
garbage = fileHandle.readline() 
fileHandle.seek ( 0 ) 
print fileHandle.readline() # "This is a test." 
fileHandle.close()
Copy after login

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 ( &#39;test.txt&#39; ) 
print fileHandle.readline() # "This is a test." 
print fileHandle.tell() # "17" 
print fileHandle.readline() # "Really, it is."
Copy after login

or read a few bytes at a time in the file:

fileHandle = open ( &#39;test.txt&#39; ) 
print fileHandle.read ( 1 ) # "T" 
fileHandle.seek ( 4 ) 
print FileHandle.read ( 1 ) # " "(原文有错)
Copy after login

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 ( &#39;testBinary.txt&#39;, &#39;wb&#39; )
fileHandle.write ( &#39;There is no spoon.&#39; )
fileHandle.close()
fileHandle = open ( &#39;testBinary.txt&#39;, &#39;rb&#39; )
print fileHandle.read()
fileHandle.close()
Copy after login

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 ( &#39;test.txt&#39; ) 
fileInfo = { 
  &#39;Size&#39; : fileStats [ stat.ST_SIZE ], 
  &#39;LastModified&#39; : time.ctime ( fileStats [ stat.ST_MTIME ] ), 
  &#39;LastAccessed&#39; : time.ctime ( fileStats [ stat.ST_ATIME ] ), 
  &#39;CreationTime&#39; : time.ctime ( fileStats [ stat.ST_CTIME ] ), 
  &#39;Mode&#39; : fileStats [ stat.ST_MODE ] 
} 
for infoField, infoValue in fileInfo: 
  print infoField, &#39;:&#39; + infoValue 
if stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ): 
  print &#39;Directory. &#39;
else: 
  print &#39;Non-directory.&#39;
Copy after login

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 ( &#39;test.txt&#39; ) 
fileMode = fileStats [ stat.ST_MODE ] 
if stat.S_ISREG ( fileStats [ stat.ST_MODE ] ): 
  print &#39;Regular file.&#39;
elif stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ): 
  print &#39;Directory.&#39;
elif stat.S_ISLNK ( fileStats [ stat.ST_MODE ] ): 
  print &#39;Shortcut.&#39;
elif stat.S_ISSOCK ( fileStats [ stat.ST_MODE ] ): 
  print &#39;Socket.&#39;
elif stat.S_ISFIFO ( fileStats [ stat.ST_MODE ] ): 
  print &#39;Named pipe.&#39;
elif stat.S_ISBLK ( fileStats [ stat.ST_MODE ] ): 
  print &#39;Block special device.&#39;
elif stat.S_ISCHR ( fileStats [ stat.ST_MODE ] ):
Copy after login

In addition, we can use "os.path" to get basic information:

import os.path 
fileStats = &#39;test.txt&#39;
if os.path.isdir ( fileStats ): 
  print &#39;Directory.&#39;
elif os.path.isfile ( fileStats ): 
  print &#39;File.&#39;
elif os.path.islink ( fileStats ): 
  print &#39;Shortcut.&#39;
elif os.path.ismount ( fileStats ): 
  print &#39;Mount point.&#39;
import os 
for fileName in os.listdir ( &#39;/&#39; ): 
  print fileName
Copy after login

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 ( &#39;testDirectory&#39; )
Copy after login

Delete the directory just created:

import os 
os.rmdir ( &#39;testDirectory )
Copy after login

You can also create multi-level directories :

import os
os.makedirs ( &#39;I/will/show/you/how/deep/the/rabbit/hole/goes&#39; )
    os.makedirs ( &#39;I/will/show/you/how/deep/the/rabbit/hole/goes&#39; )
Copy after login

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 ( &#39;I/will/show/you/how/deep/the/rabbit/hole/goes&#39;
Copy after login

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 ( &#39;/&#39; ):
  if fnmatch.fnmath ( fileName, &#39;*.txt&#39; ):
    print open ( fileName ).read()
  elif fnmatch.fnmatch ( fileName, &#39;*.exe&#39; ):
    print fileName
Copy after login

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 ( &#39;/&#39; ):
  if fnmatch.fnmatch ( fileName, &#39;?.txt&#39; ):
    print &#39;Text file.&#39;
Copy after login

The "fnmatch" module supports regular expressions:

import fnmatch 
import os 
import re 
filePattern = fnmatch.translate ( &#39;*.txt&#39; ) 
for fileName in os.listdir ( &#39;/&#39; ): 
  if re.match ( filePattern, fileName ): 
    print &#39;Text file.&#39;
Copy after login

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 ( &#39;*.txt&#39; ): 
  print &#39;Text file.&#39;
Copy after login

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 ( &#39;[0-9].txt&#39; ): 
  print filename
Copy after login

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 ( &#39;pickleFile.txt&#39;, &#39;w&#39; ) 
testList = [ &#39;This&#39;, 2, &#39;is&#39;, 1, &#39;a&#39;, 0, &#39;test.&#39; ] 
pickle.dump ( testList, fileHandle ) 
fileHandle.close()
Copy after login

It’s also not difficult to split the group:

import pickle 
fileHandle = open ( &#39;pickleFile.txt&#39; ) 
testList = pickle.load ( fileHandle ) 
fileHandle.close()
Copy after login

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 ( &#39;pickleFile.txt&#39; ) 
testList = pickle.load ( fileHandle ) 
fileHandle.close()
Copy after login

如上所述,使用Python的"pickle"模块编组确实很简单。众多对象可以通过它来存储到文件中。如果可以的话,"cPickle"同样胜任这个工作。它和"pickle"模块一样,但是速度更快:

import cPickle 
fileHandle = open ( &#39;pickleFile.txt&#39;, &#39;w&#39; ) 
cPickle.dump ( 1776, fileHandle ) 
fileHandle.close()
Copy after login

五、创建"虚拟"文件

你用到的许多模块包含需要文件对象作为参数的方法。但是,有时创建并使用一个真实的文件并让人感到有些麻烦。所幸的是,在Python中,你可以使用"StringIO"模块来创建文件并将其保存在内存中:

import StringIO 
fileHandle = StringIO.StringIO ( "Let freedom ring" ) 
print fileHandle.read() # "Let freedom ring." 
fileHandle.close()
Copy after login

cStringIO"模块同样有效。它的使用方法和"StringIO"一样,但就像"cPickle"之于"pickle",它速度更快:

import cStringIO 
fileHandle = cStringIO.cStringIO ( "To Kill a Mockingbird" ) 
print fileHandle.read() # "To Kill a Mockingbid" 
fileHandle.close()
Copy after login

结论

文件管理,是众多编程语言的程序员在编写应用程序是经常遇到的问题。幸好,和其它语言相比,Python使其出乎意料地容易。Python的标准库中提供了许多相关的模块帮助程序员解决这方面的问题,而它的面向对象的机制也简化了操作。

好了,现在你已经了解了Python中文件管理的基本知识,可以在今后的应用程序中很好地使用了。

希望本文所述对大家Python程序设计有所帮助。

更多Python 文件管理实例详解相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template