Python File Management Example detailed

Source: Internet
Author: User
Tags glob
The example in this article describes how Python file management is managed. Share to everyone for your reference, as follows:

I. 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 to other languages.
Below, Peyton McCullough explains the basics of document management.

Introduced

You have played a game using files to save the archive; Your order is saved in a file; Obviously, the report you wrote in the morning is also saved in the file.

File management is an important part of many applications written in almost any language. Python, of course, is no exception. In this article, we will explore how to use some modules to manipulate files. We will complete the reading of files, write files, increase the contents of the operation of the file, there are some alternative usage. OK, let's get started.

Read and write files

The most basic file operation is of course to read and write data in the file. This is also very easy to grasp. Now open a file for the write operation:
Copy the Code code as follows:

FileHandle = open (' Test.txt ', ' W ')

' W ' means that the file will be written to the data, and the other parts of the statement are well understood. The next step is to write the data to the file:
Copy the Code code as follows:

Filehandle.write (' This was a test.\nreally, it is. ')

This statement will "this is a test." Write the first line of the file, "really, it is." Writes the second line of the file. Finally, we need to do cleanup work and close the file:

Copy the Code code as follows:

Filehandle.close ()

As you can see, this is really very simple under the object-oriented mechanism of Python. Note that when you use the "W" method to write data in a file again, all the original content is deleted. If you want to keep the original content, you can use the "a" method to append the data to the end of the file:

FileHandle = open (' Test.txt ', ' a ')  filehandle.write (' \n\nbottom line. ')  

We then read the Test.txt and display the contents:

FileHandle = open (' test.txt ')  print filehandle.read ()  

The above statement reads the entire file and displays 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 ()

You can also save the contents of a file to a list:

FileHandle = open (' test.txt ')  fileList = Filehandle.readlines () for  fileline in fileList:    print ' >> ' , Fileline  

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

FileHandle = open (' test.txt ')  garbage = Filehandle.readline ()  

As you can see, only the second line shows up. However, we can let Python read from scratch to solve this problem:

FileHandle = open (' test.txt ')  garbage = Filehandle.readline ()  filehandle.seek (0)  print Filehandle.readl INE () # "This is a test."  Filehandle.close ()

In the above example, we let Python start reading data from the first byte of the file. So, the first line of text shows up. 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 () # "page"  print filehandle.readline () # "Really, it is."

Or read the contents of a few bytes at a time in a file:

FileHandle = open (' test.txt ')  print Filehandle.read (1) # "T"  Filehandle.seek (4)  

In Windows and Macintosh environments, it may sometimes be necessary to read and write files, tablets, and executables in binary mode. At this point, simply add a "B" to the mode parameter of the open file:

FileHandle = open (' TestBinary.txt ', ' WB ') filehandle.write (' There is no spoon. ') Filehandle.close () filehandle = open (' TestBinary.txt ', ' RB ') print Filehandle.read () filehandle.close ()

Ii. obtaining information from existing documents

Using the modules in Python, you can get 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  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 that contains basic information about a file. It then displays the relevant information and tells us whether the open is a directory. We can also try to open whether there are several other 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]):    

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 (fil eStats):    print ' File. ' Elif Os.path.islink (filestats):    print ' Shortcut. ' Elif os.path.ismount (filestats): 
  print ' Mount point. ' Import os for  fileName in Os.listdir ('/'):    

As you can see, this is simple, with three lines of code to complete.

Creating a directory is also simple:

Import OS  

Delete the directory you just created:

Import OS  os.rmdir (' testdirectory)

You can also create a multilevel 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 don't add anything in the folder you created, you can delete all of them at once (that is, delete all the empty folders listed):

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

When you need to operate on a particular file type, we can select the "Fnmatch" module. The following is the file name that displays the contents of the ". txt" files and the ". exe" FILE:

Import Fnmatchimport osfor fileName in Os.listdir ('/'):  if Fnmatch.fnmath (fileName, ' *.txt '):    print open (f Ilename). Read ()  elif fnmatch.fnmatch (fileName, ' *.exe '):    print FileName

Characters can represent any length of character. If you want to match one character, use the "?" 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 the module is similar to "Fnmatch":

Import Glob for  fileName in Glob.glob (' *.txt '):    

Using a range of characters to match is also possible, just as it is used in regular expressions. Let's say you want to display the file name with only one digit before the extension:

Import Glob for  fileName in Glob.glob (' [0-9].txt '):    

The "Glob" module is implemented using the "Fnmatch" module.

Iv. Data Grouping

Using the modules described in the previous section, you can read and write strings in a file.

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 to do this. You can use the "pickle" module in the Python standard library to complete the data grouping.

Next, let's group A list that contains strings and numbers:

Import pickle  filehandle = open (' PickleFile.txt ', ' W ')  testlist = [' This ', 2, ' is ', 1, ' A ', 0, ' test. '  ) Pickle.dump (Testlist, FileHandle)  

Splitting a group is also not difficult:

Import pickle  filehandle = open (' pickleFile.txt ')  testlist = Pickle.load (filehandle)  

Now try to store more complex data:

Import pickle  filehandle = open (' PickleFile.txt ', ' W ')  testlist = [123, {' Calories ':}, ' Mr Anderson ', [1, 2, 7]  Pickle.dump (Testlist, FileHandle)  filehandle.close () import pickle  filehandle = open (' PickleFile.txt ')  Testlist = Pickle.load (filehandle)  

As mentioned above, using Python's "pickle" module grouping is really simple. Many objects can be stored in a file by it. If possible, "Cpickle" is equally qualified for the job. It is the same as the "pickle" module, but faster:

Import cpickle  filehandle = open (' PickleFile.txt ', ' W ')  cpickle.dump (1776, FileHandle)  

V. Create a "virtual" file

Many of the modules you use contain methods that require a file object as a parameter. However, sometimes it is difficult to create and use a real file. Fortunately, in Python, you can use the "Stringio" module to create a file and save it in memory:

Import Stringio  filehandle = Stringio.stringio ("Let Freedom Ring")  print Filehandle.read () # "Let Freedom Ring." "  

Cstringio "module is also valid. It uses the same method 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 "  

Conclusion

File management is a problem that programmers in many programming languages often encounter when writing applications. Fortunately, Python makes it surprisingly easy to compare with other languages. Python's standard library provides a number of related modules to help programmers solve this problem, and its object-oriented mechanism simplifies the operation.

Well, now that you've learned the basics of file management in Python, it's good to use in future applications.

I hope this article is helpful for Python program design.

  • 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.