Python file management instance details,

Source: Internet
Author: User
Tags glob

Python file management instance details,

This document describes how to manage Python files. We will share this with you for your reference. The details are as follows:

1. File Management in Python

File Management is a basic function and an important part of many applications. Python makes file management extremely simple, especially compared with other languages.
Below, Peyton McCullough explains the basics of file management.

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 is no exception. In this article, we will explore how to use some modules to operate files. We will complete operations such as reading files, writing files, and adding file content. There are also some alternative usage. OK. Let's get started.

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:
Copy codeThe Code is as follows: fileHandle = open ('test.txt ', 'w ')

'W' indicates that the file will be written into data, and the rest of the statement is easy to understand. The next step is to write data to a file:
Copy codeThe Code is as follows: 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 clear the file and close the file:

Copy codeThe Code is as follows: 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:

fileHandle = open ( 'test.txt', 'a' )  fileHandle.write ( '\n\nBottom line.' )  fileHandle.close() 

Then we read test.txt and show the content:

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 the file:

fileHandle = open ( 'test.txt' )  print fileHandle.readline() # "This is a test."  fileHandle.close()

You 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() 

When reading a file, Python remembers its location in the file as follows:

fileHandle = open ( 'test.txt' )  garbage = fileHandle.readline()  fileHandle.readline() # "Really, it is."fileHandle.close() 

We can see that only the second row is displayed. However, we can let Python read from the beginning to solve this problem:

fileHandle = open ( 'test.txt' )  garbage = fileHandle.readline()  fileHandle.seek ( 0 )  print fileHandle.readline() # "This is a test."  fileHandle.close()

In the above example, let Python read data from the first byte of the file. Therefore, the first line of text is displayed. Of course, we can also obtain 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 several bytes of content in the file at a time:

FileHandle = open ('test.txt ') print fileHandle. read (1) # "T" fileHandle. seek (4) print FileHandle. read (1) # "(the original article is wrong)

In Windows and Macintosh environments, you may sometimes need to read and write files in binary mode, such as chips and executable files. In this case, you only need to add a "B" to the file opening method parameter:

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 the Python module to obtain information from an existing file. You can use the "OS" module and "stat" module to obtain the basic information of 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.'

In the preceding example, a dictionary containing the basic information of the file is created. Then the information is displayed, and whether the opened directory is used. We can also try to see if the opened items are of the following types:

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 obtain 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 with three lines of code.

Creating a directory is also simple:

import os  os.mkdir ( 'testDirectory' ) 

Delete the Created directory:

import os  os.rmdir ( 'testDirectory )

You can also create a multi-level directory:

import osos.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 have not added anything to the created folder, you can delete all the items at one time (that is, delete all the empty folders listed in ):

import osos.removedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes'

When you need to operate a specific file type, you can select the "fnmatch" module. The following shows the content of the ". txt" file and the file name of the ". exe" file:

import fnmatchimport osfor fileName in os.listdir ( '/' ):  if fnmatch.fnmath ( fileName, '*.txt' ):    print open ( fileName ).read()  elif fnmatch.fnmatch ( fileName, '*.exe' ):    print fileName

Characters can be any length of characters. If you want to match a character, use "? "Symbol:

import fnmatchimport osfor 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 you only need to match one type of file, a better way is to use the "glob" module. The format of this module is similar to that of "fnmatch:

import glob  for fileName in glob.glob ( '*.txt' ):    print 'Text file.' 

It is equally feasible to use a certain range of characters for matching, just as it is used in regular expressions. Suppose you want to display the file name with only one digit before the extension:

import glob  for fileName in glob.glob ( '[0-9].txt' ):    print filename 

The "glob" module is implemented using the "fnmatch" module.

Iv. Data grouping

The modules described in the previous section can be used to 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 use Pickling. You can use the "pickle" module in the Python standard library to group data.

Next, we will 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() 

Splitting groups is equally difficult:

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() 

As mentioned above, it is really easy to group "pickle" modules using Python. Many objects can be stored in files. If you can, "cPickle" is also competent for this job. It is the same as the "pickle" module, but the speed is faster:

import cPickle  fileHandle = open ( 'pickleFile.txt', 'w' )  cPickle.dump ( 1776, fileHandle )  fileHandle.close() 

5. Create a "virtual" File

Many modules you use include methods that require file objects as parameters. However, sometimes it is troublesome to create and use a real file. Fortunately, in Python, you can use the "StringIO" module to create a file and save it in the memory:

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

The cStringIO module is also valid. It is used in the same way as "StringIO", but like "cPickle" to "pickle", it is faster:

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

Conclusion

File Management is a problem that programmers in many programming languages often encounter when writing applications. Fortunately, compared with other languages, Python makes it unexpectedly easy. The Python Standard Library provides many related modules to help programmers solve this problem, and its object-oriented mechanism also simplifies operations.

Now you know the basic knowledge of file management in Python and can use it well in future applications.

I hope this article will help you with Python programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.