Python file input and output operations

Source: Internet
Author: User


You can create a file class object to open a file and use the read, readline, or write methods of the file class to read and write the file properly. The ability to read and write files depends on the mode specified when you open the file. Finally, when you complete file operations, you call the close method to tell Python that we have used the file.

Use files


#! /Usr/bin/python
# Filename: using_file.py
 
Poem = '''\
Programming is fun
When the work is done
If you wanna make your work also fun:
Use Python!
'''
 
F = file('poem.txt ', 'w') # open for 'W' riting
F. write (poem) # write text to file
F. close () # close the file
 
F = file('poem.txt ')
# If no mode is specified, 'R' ead mode is assumed by default
While True:
Line = f. readline ()
If len (line) = 0: # Zero length indicates EOF
Break
Print line,
# Notice comma to avoid automatic newline added by Python
F. close () # close the file
$ Python using_file.py
Programming is fun
When the work is done
If you wanna make your work also fun:
Use Python!

First, we create a file class instance by specifying the files and modes we want to open. The mode can be read ('r'), write ('w'), or append ('A '). In fact, there are many more modes to use. You can use help (file) to learn more about them.
We first open the file in write mode, then use the write method of the file class to write the file, and finally close the file with close.
Next, we will open the same file again to read the file. If no mode is specified, the Read mode is used as the default mode. In a loop, we use the readline method to read each row of the file. This method returns a complete line that includes the last line break. Therefore, when an empty string is returned, it indicates that the end of the file has reached, so we stop the loop.
Note: Because the content read from the file has ended with a line break, we use a comma in the print statement to remove automatic line breaks. Finally, close the file.
Storage


Python provides a standard module called pickle. Using it, you can store any Python object in a file, and then you can retrieve it completely. This is called a persistent storage object.
Another module, cPickle, has the same functions as the pickle module, except that it is written in C, so it is much faster (1000 times faster than pickle ). You can use either of them, and here we will use the cPickle module. Remember, we can refer to the two modules as pickle modules.

Storage and Retrieval

#! /Usr/bin/python
# Filename: pickling. py
 
Import cPickle as p
# Import pickle as p
 
Shoplistfile = 'shoplist. Data'
# The name of the file where we will store the object
 
Shoplist = ['apple', 'Mango', 'carrot']
 
# Write to the file
F = file (shoplistfile, 'w ')
P. dump (shoplist, f) # dump the object to a file
F. close ()
 
Del shoplist # remove the shoplist
 
# Read back from the storage
F = file (shoplistfile)
Storedlist = p. load (f)
Print storedlist
$ Python pickling. py
['Apple ', 'Mango', 'carrot']

First, note that we use the import... as syntax. This is a convenient method so that we can use shorter module names. In this example, it also enables us to switch to another module (cPickle or pickle) by simply changing one line )! In the rest of the program, we simply call this module p.

To store an object in a file, first open a file object in write mode, then call the dump function of the storage module to store the object to the opened file. This process is called storage.

You can't remember the API. I used this when I wrote it last night, but I didn't remember it, so I simply sorted it out:

Operations on files and folders (File operation functions) in python involve the OS module and the shutil module.

Get the current working directory, that is, the directory path for the current Python script: OS. getcwd ()

Returns all files and directories in the specified directory named OS. listdir ()

The function is used to delete a file: OS. remove ()

Delete multiple directories: OS. removedirs (r "c: \ python ")

Check whether the given path is a file: OS. path. isfile ()

Check whether the given path is a directory: OS. path. isdir ()

Determine whether the path is absolute: OS. path. isabs ()

Check whether the given path is saved: OS. path. exists ()

Returns the directory name and file name of a path: OS. path. split () eg OS. path. split ('/home/swaroop/byte/code/poem.txt') result: ('/home/swaroop/byte/code', 'poem.txt ')

Separation extension: OS. path. splitext ()

Get the path: OS. path. dirname ()

Get File name: OS. path. basename ()

Run the shell command: OS. system ()

Read and set environment variables: OS. getenv () and OS. putenv ()

The line terminator used by the current platform is given: OS. linesep for Windows uses '\ r \ n', Linux uses' \ n', and Mac uses '\ r'

Indicates the platform you are using: OS. name for Windows, it is 'nt ', and for Linux/Unix users, it is 'posix'

Rename: OS. rename (old, new)

Create a multilevel Directory: OS. makedirs (r "c: \ python \ test ")

Create a single directory: OS. mkdir ("test ")

Get file attributes: OS. stat (file)

Modify file permission and timestamp: OS. chmod (file)

Terminate the current process: OS. exit ()

Get file size: OS. path. getsize (filename)


File operations:
OS. mknod ("test.txt") to create an empty file
Fp = open ("test.txt", w) open a file directly. If the file does not exist, create a file.

About open mode:

W open in write mode,
A is opened in append mode (starting from EOF and creating a file if necessary)
R + enabled in read/write mode
W + is enabled in read/write mode (see w)
A + is enabled in read/write mode (see)
Rb is enabled in binary read mode.
Wb is enabled in binary write mode (see w)
AB is enabled in binary append mode (see)
Rb + is enabled in binary read/write mode (see r +)
Wb + is enabled in binary read/write mode (see w +)
AB + is enabled in binary read/write mode (see a +)

 

Fp. read ([size]) # size indicates the read length, in bytes.

Fp. readline ([size]) # read a row. If the size is defined, only one part of the row may be returned.

Fp. readlines ([size]) # use each row of the file as a member of a list and return this list. In fact, it is implemented by calling readline () cyclically. If the size parameter is provided, size indicates the total length of the read content, that is, it may be read only to a part of the file.

Fp. write (str) # write str to the file. write () does not add a linefeed after str.

Fp. writelines (seq) # write all seq content to a file (multiple rows are written at one time ). This function is only faithfully written without adding anything to the end of each line.

Fp. close () # close the file. Python will automatically close the file after a file is not used, but this function is not guaranteed, it is best to develop your own habit of closing. If a file is closed and operated on it, ValueError is generated.

Fp. flush () # write the buffer content to the hard disk

Fp. fileno () # returns a long integer "file tag"

Fp. isatty () # whether the file is a terminal device file (in unix)

Fp. tell () # return the current position of the file operation mark, starting with the file as the origin

Fp. next () # return the next line and move the operation mark of the file to the next line. Use a file... When a statement such as in file is called, the next () function is called to implement traversal.

Fp. seek (offset [, whence]) # Mark the file operation and move it to the offset position. This offset is generally calculated relative to the beginning of the file, and is generally a positive number. However, if the whence parameter is provided, it is not necessary. If The whence parameter is 0, it indicates that the calculation starts from the beginning, and 1 indicates that the calculation is based on the current position. 2 indicates that the origin is the end of the file. Note that if the file is opened in a or a + mode, the operation mark of the file is automatically returned to the end of the file each time the file is written.

Fp. truncate ([size]) # crop the file to the specified size. The default value is the location marked by the current file operation. If the size is larger than the file size, the file may not be changed depending on the system, or 0 may be used to fill the file with the corresponding size, it may also be added with random content.

 

Directory operation:
OS. mkdir ("file") to create a directory
Copy a file:
Shutil. copyfile ("oldfile", "newfile") both oldfile and newfile can only be files.
Shutil. copy ("oldfile", "newfile") oldfile can only be a folder. newfile can be a file or a target directory.
Copy folder:
Shutil. copytree ("olddir", "newdir") both olddir and newdir can only be directories, and newdir must not exist
Rename a file (directory)
OS. rename ("oldname", "newname") files or directories all use this command
Move a file (directory)
Shutil. move ("oldpos", "newpos ")
Delete an object
OS. remove ("file ")
Delete directory
OS. rmdir ("dir") can only delete empty directories
Shutil. rmtree ("dir") empty directories and directories with content can be deleted.
Conversion Directory
OS. chdir ("path") change path

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.