Python file operations read and write files

Source: Internet
Author: User
Tags glob

From: http://maincoolbo.iteye.com/blog/626655

I. 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:

1. fileHandle = open ('test.txt ', 'w ')

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:

1. 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 clear the file and close the file:

1. 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:

1. fileHandle = open ('test.txt ', 'A ')
2. fileHandle. write ('\ n \ nBottom line .')
3. fileHandle. close ()

FileHandle = open ('test.txt ', 'A ')
FileHandle. write ('\ n \ nBottom line .')
FileHandle. close ()

Then we read test.txt and show the content:

1. fileHandle = open ('test.txt ')
2. print fileHandle. read ()
3. 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 the file:

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

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

You can also save the file content to a list:

1. fileHandle = open ('test.txt ')
2. fileList = fileHandle. readlines () <div> </div>
3. for fileLine in fileList:
4. print '>', fileLine
5. fileHandle. close ()

FileHandle = open ('test.txt ')
FileList = fileHandle. readlines ()
For fileLine in fileList:
Print '>', fileLine
FileHandle. close ()

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

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

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:

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

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:

1. fileHandle = open ('test.txt ')
2. print fileHandle. readline () # "This is a test ."
3. print fileHandle. tell () # "17"
4. print fileHandle. readline () # "Really, it is ."

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:

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

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

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:

1. fileHandle = open ('testBinary.txt ', 'wb ')
2. fileHandle. write ('there is no spoon .')
3. fileHandle. close ()

FileHandle = open ('testBinary.txt ', 'wb ')
FileHandle. write ('there is no spoon .')
FileHandle. close ()

1. fileHandle = open ('testBinary.txt ', 'rb ')
2. print fileHandle. read ()
3. fileHandle. close ()

FileHandle = open ('testBinary.txt ', 'rb ')
Print fileHandle. read ()
FileHandle. close ()


Use the Python module to obtain information from an existing file. The "OS" module and the "stat" module can be used to obtain basic information about the file:

1. import OS
2. import stat
3. import time <div> </div>
4.
5. fileStats = OS. stat ('test.txt ')
6. fileInfo = {
7. 'SIZE': fileStats [stat. ST_SIZE],
8. 'lastmodified': time. ctime (fileStats [stat. ST_MTIME]),
9. 'lastaccesssed ': time. ctime (fileStats [stat. ST_ATIME]),
10. 'creationtime': time. ctime (fileStats [stat. ST_CTIME]),
11. 'Mode': fileStats [stat. ST_MODE]
12 .}
13.
14. for infoField, infoValue in fileInfo:
15. print infoField, ':' + infoValue
16. if stat. S_ISDIR (fileStats [stat. ST_MODE]):
17. print 'directory .'
18. else:
19. print 'non-directory .'

Import OS
Import stat
Import time

FileStats = OS. stat ('test.txt ')
FileInfo = {
'SIZE': fileStats [stat. ST_SIZE],
'Lastmodified': time. ctime (fileStats [stat. ST_MTIME]),
'Lastaccesss': 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:

1. import OS
2. import stat
3.
4. fileStats = OS. stat ('test.txt ')
5. fileMode = fileStats [stat. ST_MODE]
6. if stat. S_ISREG (fileStats [stat. ST_MODE]):
7. print 'regular file .'
8. elif stat. S_ISDIR (fileStats [stat. ST_MODE]):
9. print 'directory .'
10. elif stat. S_ISLNK (fileStats [stat. ST_MODE]):
11. print 'cut cut .'
12. elif stat. S_ISSOCK (fileStats [stat. ST_MODE]):
13. print 'socket .'
14. elif stat. S_ISFIFO (fileStats [stat. ST_MODE]):
15. print 'named pipe .'
16. elif stat. S_ISBLK (fileStats [stat. ST_MODE]):
17. print 'block special device .'
18. elif stat. S_ISCHR (fileStats [stat. ST_MODE]):
19. print 'character special device .'

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]):
Print 'character special device .'

In addition, we can use "OS. path" to obtain basic information:

1. import OS. path
2.
3. fileStats = 'test.txt'
4. if OS. path. isdir (fileStats ):
5. print 'directory .'
6. elif OS. path. isfile (fileStats ):
7. print 'file .'
8. elif OS. path. islink (fileStats ):
9. print 'cut cut .'
10. elif OS. path. ismount (fileStats ):
11. print 'mount point .'

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

Iii. Directory
Like common files, directory operations are easy to understand. First, list the contents of a directory:

1. import OS
2.
3. for fileName in OS. listdir ('/'):
4. print fileName

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:

1. import OS
2.
3. OS. mkdir ('testdirectory ')

Import OS

OS. mkdir ('testdirectory ')

Delete the Created directory:

1. import OS
2.
3. OS. rmdir ('testdirectory)

Import OS

OS. rmdir ('testdirectory)

Well, you can create multi-level directories:

1. import OS
2.
3. OS. makedirs ('I/will/show/you/how/deep/the/rabbit/hole/goes ')

Import OS

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

1. import OS
2.
3. OS. removedirs ('I/will/show/you/how/deep/the/rabbit/hole/goes ')

Import OS

OS. 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 is the file name that displays the volume of the. txt file and the volume of the. txt file:

1. import fnmatch
2. import OS
3.
4. for fileName in OS. listdir ('/'):
5. if fnmatch. fnmath (fileName, '*. txt '):
6. print open (fileName). read ()
7. elif fnmatch. fnmatch (fileName, '*. exe '):
8. print fileName

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

The "*" character can represent any length of characters. If you want to match a character, use "?" Symbol:

1. import fnmatch
2. import OS
3.
4. for fileName in OS. listdir ('/'):
5. if fnmatch. fnmatch (fileName ,'?. Txt '):
6. print 'text file .'

Import fnmatch
Import OS

For fileName in OS. listdir ('/'):
If fnmatch. fnmatch (fileName ,'?. Txt '):
Print 'text file .'

The fnmatch module supports regular expressions:

1. import fnmatch
2. import OS
3. import re
4.
5. filePattern = fnmatch. translate ('*. txt ')
6. for fileName in OS. listdir ('/'):
7. if re. match (filePattern, fileName ):
8. print 'text file .'

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, the better way is to use the "glob" module. The format of this module is similar to that of "fnmatch:

1. import glob
2.
3. for fileName in glob. glob ('*. txt '):
4. print 'text file .'

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:

1. import glob
2.
3. for fileName in glob. glob ('00000-90000.txt '):
4. print filename

Import glob

For fileName in glob. glob ('00000-90000.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:

1. import pickle
2.
3. fileHandle = open ('pickleFile.txt ', 'w ')
4. testList = ['eas', 2, 'is ', 1, 'A', 0, 'test.']
5. pickle. dump (testList, fileHandle)
6. fileHandle. close ()

Import pickle

FileHandle = open ('pickleFile.txt ', 'w ')
TestList = ['eas', 2, 'is ', 1, 'A', 0, 'test.']
Pickle. dump (testList, fileHandle)
FileHandle. close ()

Splitting groups is equally difficult:

1. import pickle
2.
3. fileHandle = open ('pickleFile.txt ')
4. testList = pickle. load (fileHandle)
5. fileHandle. close ()

Import pickle

FileHandle = open ('pickleFile.txt ')
TestList = pickle. load (fileHandle)
FileHandle. close ()

Now try to store more complex data:

1. import pickle
2.
3. fileHandle = open ('pickleFile.txt ', 'w ')
4. testList = [123, {'calories ': 190}, 'Mr. Anderson', [1, 2, 7]
5. pickle. dump (testList, fileHandle)
6. fileHandle. close ()

Import pickle

FileHandle = open ('pickleFile.txt ', 'w ')
TestList = [123, {'calories ': 190}, 'Mr. Anderson', [1, 2, 7]
Pickle. dump (testList, fileHandle)
FileHandle. close ()

1. import pickle
2.
3. fileHandle = open ('pickleFile.txt ')
4. testList = pickle. load (fileHandle)
5. fileHandle. close ()

Import pickle

FileHandle = open ('pickleFile.txt ')
TestList = pickle. load (fileHandle)
FileHandle. close ()

As mentioned above, it is really easy to use Python's "pickle" module grouping. Many objects can be stored in files. If possible, "cPickle" is also competent for the job. It is the same as the "pickle" module, but the speed is faster:

1. import cPickle
2.
3. fileHandle = open ('pickleFile.txt ', 'w ')
4. cPickle. dump (1776, fileHandle)
5. fileHandle. close ()

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:

1. import StringIO
2.
3. fileHandle = StringIO. StringIO ("Let freedom ring ")
4. print fileHandle. read () # "Let freedom ring ."
5. fileHandle. close ()

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" for "pickle", it is faster:

1. import cStringIO
2.
3. fileHandle = cStringIO. cStringIO ("To Kill a Mockingbird ")
4. print fileHandle. read () # "To Kill a Mockingbid"
5. fileHandle. close ()

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.

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.