Python getting started

Source: Internet
Author: User
Tags glob
Files are the places where we store information. we often need to read, write, and delete files. in Python, we can use functions and methods provided by Python to conveniently operate files. Files can be opened by calling open or file. open is generally more common than file, because file processing functions and methods

Use the Open () function to Open a file. the syntax format is as follows:

The code is as follows:


File_handler = open (filename, [, mode [, bufsize]

Filename is the name of the file to be operated. if it is not in the current path, you must specify the specific path. Mode is the mode for opening a file, indicating how you want to operate the file, and bufsize indicates whether to use the cache.

Mode

Mode Description
R Open the file in read mode to read the file information.
W Open the file in write mode and write information to the file.
A Open the file in append mode, and the file pointer is automatically moved to the end of the file.
R + Open a file in read/write mode to read and write the file.
W + Remove the file content and open the file in read/write mode.
A + Open the file in read/write mode, and move the file pointer to the end of the file.
B Open the file in binary mode, instead of text mode. This mode is only valid for Windows or Dos, and Unix-like files are operated in binary mode.

Bufsize

Bufsize value Description
0 Disable Buffering
1 Row buffer
> 1 Specify the buffer size
<1 Default system buffer size

The open () function returns a file object. we can use the read () or write () function to read and write the file. Below are some file object methods:

File object method

Method Description
F. close () Close the file. remember to close the file after opening it with open (). Otherwise, it will occupy the number of accessible file handles of the system.
F. fileno () Get file descriptor
F. flush () Refresh Output cache
F. isatty () If the file is an interactive terminal, True is returned; otherwise, False is returned.
F. read ([count]) Read the file. if there is count, read count bytes.
F. readline () Read a row of information.
F. readlines () Read all rows, that is, read the information of the entire file.
F. seek (offset [, where]) Move the file pointer to the offset position relative to where. 0 indicates the start of the file, which is the default value; 1 indicates the current position; 2 indicates the end of the file.
F. tell () Obtain the file pointer position.
F. truncate ([size]) Truncate the file to make it size.
F. write (string) Writes a string to a file.
F. writelines (list) Write the string in the list into the file one by one row.

Example

1. open or create a file

The code is as follows:


#! /Usr/bin/env python
#-*-Encoding: UTF-8 -*-

Filehandler = open('test.txt ', 'w') # open the file in write mode. if the file does not exist, create
Filehandler. write ('This is a file open/create test. \ nthe second line .')

Filehandler. close ()
#! /Usr/bin/env python
#-*-Encoding: UTF-8 -*-

Filehandler = open('test.txt ', 'A') # open the file in append mode. if the file does not exist, create

Filehandler. write ('\ nappend the text in another line. \ n ')

Filehandler. close ()

2. read files

The code is as follows:


#! /Usr/bin/env python
#-*-Encoding: UTF-8 -*-

Filehandler = open('test.txt ', 'r') # open a file in read mode, and rb is in binary mode (segment or executable file, etc)

Print 'read () function: '# read the entire file
Print filehandler. read ()

Print 'readline () function: '# return the file header and read a row
Filehandler. seek (0)
Print filehandler. readline ()

Print 'readlines () function: '# returns the file header and the list of all rows.
Filehandler. seek (0)
Print filehandler. readlines ()

Print 'list all lines' # return the file header, displaying all rows
Filehandler. seek (0)
Textlist = filehandler. readlines ()
For line in textlist:
Print line

Print 'seek () function' # shift to 32nd characters and display the remaining content starting from 33 characters
Filehandler. seek (32)
Print filehandler. read ()

Print 'Tell () function' # shift to the file header and display 2 characters from the beginning
Filehandler. seek (0)
Print filehandler. readline () # display the first line of content
Print filehandler. tell () # display the current location
Print filehandler. readline () # display the second line of content
Print filehandler. read () # show all remaining content

Filehandler. close () # close the file handle

3. file system operations

The code is as follows:


#! /Usr/bin/env python
#-*-Encoding: UTF-8 -*-

Import OS, fnmatch, glob

For fileName in OS. listdir ('/root'): # List/root contents, excluding ..
Print fileName

OS. mkdir ('py') # Create a py directory under the current directory and create only one layer
OS. rmdir ('py') # Delete the py directory under the current directory and only one layer can be deleted
OS. makedirs ('py/AA') # you can create multiple levels of directories.
OS. removedirs ('py/AA') # you can delete multiple levels of directories.


Print 'Demo fnmatch module'
For fileName in OS. listdir ('/root/python/file '):
If fnmatch. fnmatch (fileName, '*. txt'): # Use a UNIX-style wildcard to display only txt files.
Print fileName

Print 'statement glob module'
For fileName in glob. glob ('*. txt'): # Use a UNIX-style wildcard to display only txt files.
Print fileName

4. get the file status

The code is as follows:


#! /Usr/bin/env python
#-*-Encoding: UTF-8 -*-

Import OS, time, stat

FileStats = OS. stat ('test.txt ') # obtain the file/directory status.
FileInfo = {
'Size': fileStats [stat. ST_SIZE], # obtain the file Size
'Lastmodified': time. ctime (fileStats [stat. ST_MTIME]), # obtain the last object modification time
'Lastaccesss': time. ctime (fileStats [stat. ST_ATIME]), # obtain the last object access time
'Creationtime': time. ctime (fileStats [stat. ST_CTIME]), # obtain the file creation time
'Mode': fileStats [stat. ST_MODE] # obtain the file Mode.
}
# Print fileInfo

For field in fileInfo: # display object content
Print '% s: % s' % (field, fileInfo [field])

# For infoField, infoValue in fileInfo:
# Print '% s: % s' % (infoField, infoValue)
If stat. S_ISDIR (fileStats [stat. ST_MODE]): # determine whether the path is used.
Print 'directory .'
Else:
Print 'non-directory .'

If stat. S_ISREG (fileStats [stat. ST_MODE]): # determine whether a common file is used.
Print 'regular file .'
Elif stat. S_ISLNK (fileStats [stat. ST_MODe]): # determine whether a file is linked.
Print 'Shortcut .'
Elif stat. S_ISSOCK (fileStats [stat. ST_MODe]): # determine whether a socket file is used.
Print 'socket .'
Elif stat. S_ISFIFO (fileStats [stat. ST_MODe]): # determine whether to name a pipe.
Print 'named pipe .'
Elif stat. S_ISBLK (fileStats [stat. ST_MODe]): # determine whether a block device is used.
Print 'block special device .'
Elif stat. S_ISCHR (fileStats [stat. ST_MODe]): # determines whether the character is set.
Print 'character special device .'
#! /Usr/bin/env python
#-*-Encoding: UTF-8 -*-

Import OS. path

FileStats = 'test.txt'

If OS. path. isdir (fileStats): # determine whether the path is correct.
Print 'directory .'
Elif OS. path. isfile (fileStats): # determines whether a common file is used.
Print 'File .'
Elif OS. path. islink (fileStats): # determine whether a file is linked.
Print 'Shortcut .'
Elif OS. path. ismount (fileStats): # check whether the contacts are mounted.
Print 'Mount point .'

The stat module describes the meaning of each value in the file attribute list returned by OS. stat (filename. We can easily access the values in OS. stat () based on the stat module.

5. serialized files

The code is as follows:


#! /Usr/bin/env python
#-*-Encoding: UTF-8 -*-

Import pickle

Filehandler = open('pickle.txt ', 'w ')

Text = ['This is a pickle demonstrate ', 'A', 'BB']

Pickle. dump (text, filehandler) stores the content of textcontent in the pickle.txt file.

Filehandler. close ()

Filehandler2 = open('pickle.txt ')

Textlist = pickle. load (filehandler2) # Restore a serialized string
Print textlist

Filehandler2.close ()

# Cpickle is a C-written pickle module, which is much faster than the standard pickle.

6. memory files

The code is as follows:


#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-

Import StringIO

FileHandle = StringIO. StringIO ("Let freedom ring.") # create file in memory

Print fileHandle. read () # "Let freedom ring ."

FileHandle. close ()

# CStringIO is a StringIO module written in C. the execution speed is faster than that of StringIO.

The shutil module is an advanced file processing module that allows you to copy and delete files.

Open a file
When you open a file program, it calls the built-in open function. The first is the external name, and then the processing mode.

Common file operations:

In any case, the text file in the Python program is in the form of a string. when reading the text, the text in the form of a string is returned.

The data read from the file is returned to the script as a string, so if the string is not what you need, you have to convert it to another type of Python object.

Files in actual application
First, let's look at a simple example of file processing:

The code is as follows:


>>> Myfile = open ('myfile', 'w ')
>>> Myfile. write ('Hello, myfile! \ N ')
>>> Myfile. close ()
>>> Myfile = open ('myfile ')
>>> Myfile. readline ()
'Hello, myfile! \ N'
>>> Myfile. readline ()
''

Write a line of text into a string containing the line terminator \ n. the writing method does not add a line terminator to us.

Store and parse Python objects in files
You must use the conversion tool to convert an object to a string. Note that the file data must be a string in the script, and the writing method does not automatically convert the object to the string format.

The code is as follows:


>>> X, Y, Z = 43,324, 34
>>> S = 'spam'
>>> D = {'a': 1, 'B': 2}
>>> L = [1, 2, 3]
>>> F=open('datafile.txt ', 'w ')
>>> F. write (S + '\ n ')
>>> F. write ('% s, % s, % s \ n' % (X, Y, Z ))
>>> F. write (str (L) + '$' + str (D) + '\ n ')
>>> F. close ()

Once a file is created, you can open and read strings to view the content of the file. the print statement will explain the embedded line terminator to the user's satisfaction:

The code is as follows:


>>> Bytes0000open('datafile.txt '). read ()
>>> Bytes
"Spam \ n43, 324,34 \ n [1, 2, 3] $ {'a': 1, 'B': 2} \ n"
>>> Print bytes
Spam
43,324, 34
[1, 2, 3] $ {'a': 1, 'B': 2}

Since Python does not automatically convert strings to numbers or other types of objects, common object tools such as indexing and addition are required.

The code is as follows:


>>> F=open('datafile.txt ')
>>> Line = F. readline ()
>>> Line
'Spam \ n'
>>> Line = F. readline ()
>>> Line
'2014, 34 \ n'
>>> Parts = line. split (',')
>>> Parts
['43 ', '000000', '34 \ n']
>>> Int (parts [1])
324
>>> Numbers = [int (p) for p in parts]
>>> Numbers
[43,324, 34]
>>> Line = F. readline ()
>>> Line
"[1, 2, 3] $ {'a': 1, 'B': 2} \ n"
>>> Parts = line. split ('$ ')
>>> Parts
['[1, 2, 3]', "{'a': 1, 'B': 2} \ n"]
>>> Eval (parts [0])
[1, 2, 3]
>>> Objects = [eval (p) for p in parts]
>>> Objects
[[1, 2, 3], {'a': 1, 'B': 2}]

Use pickle to store Python native objects
Eval can be used to convert a string to an object. the pickle module is an advanced tool that allows us to directly store almost any Python object in a file. it does not require string conversion.

The code is as follows:


>>> F=open('datafile.txt ', 'w ')
>>> Import pickle
>>> Pickle. dump (D, F)
>>> F. close ()
>>> F=open('datafile.txt ')
>>> E = pickle. load (F)
>>> E
{'A': 1, 'B': 2}

The pickle module implements object serialization, that is, mutual conversion between objects and byte strings.

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.