Top 10 in python --- File and basic input/output operations,

Source: Internet
Author: User

Top 10 in python --- File and basic input/output operations,

1. Python file I/O
This chapter only describes all basic I/O functions. For more functions, see the Python standard documentation.

2. Print to the screen
The simplest output method is to use the print statement. You can pass zero or multiple expressions separated by commas. This function converts your passed expression into a string expression and writes the result to the standard output as follows:

Example 1:

#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/25 # @ Author: wwyxprint "python is an object-oriented language"

The result of running example 1 is as follows:

Python is an object-oriented language.

 

3. Read keyboard input
Python provides two built-in functions to read a line of text from the standard input. The default standard input is the keyboard. As follows:

  • Raw_input
  • Input

Raw_input Function
Raw_input ([prompt]) function reads a row from the standard input and returns a string (remove the line break at the end ):
Example 2:

#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/25 # @ Author: wwyxstrs = raw_input ("Enter the string you want to enter: ") print" the string you entered is: ", strs

Example 2 running result:

Enter the string you want to enter: python the string you entered is: python

Input Function
The input ([prompt]) function is similar to the raw_input ([prompt]) function, but the input can receive a Python expression as the input and return the operation result.

Example 3:

#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/25 # @ Author: wwyxinputStr = input ("input expression :") print "run the input Result:", inputStr

Example 3 running result:

Input expression: [x * 4 for x in (2, 3, 4)] Run the input result: [8, 12, 16]

 

4. Open and Close files
Now, you can read and write to standard input and output. Now let's take a look at how to read and write the actual data files.
Python provides the necessary functions and methods for basic file operations by default. You can use a file object for most file operations.
Open Function
You must use the Python built-in open () function to open a file and create a file object before calling it for read/write.
Syntax:

file object = open(file_name [, access_mode][, buffering]

The parameters are described as follows:

  • File_name: The file_name variable is a string value that contains the name of the file you want to access.
  • Access_mode: Access_mode determines the file opening mode: Read-only, write, and append. For all values, see the complete list below. This parameter is not mandatory. The default file access mode is read-only (r ).
  • Buffering: If the buffering value is set to 0, no storage will be available. If the buffering value is set to 1, the row is stored when the file is accessed. If the buffering value is set to an integer greater than 1, it indicates the buffer size of the storage zone. If the value is negative, the buffer size in the storage area is the default value.

Complete list of open files in different modes:
Mode description

File object attributes
After a file is opened, you have a file object. You can obtain various information about the file.
The following lists all attributes related to the file object:
Attribute description

  • File. closedReturns true if the object is closed; otherwise, returns false.
  • File. modeReturns the access mode of the opened file.
  • File. nameThe name of the returned file.
  • File. softspaceIf the print output must be followed by a space character, 0 is returned. Otherwise, 1 is returned.

Example 4

#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/25 # @ Author: wwyxfiletest = open ("file.txt", "wb ") print "Whether the file is closed:", filetest. closedprint "file mode:", filetest. modeprint "file name:", filetest. nameprint "whether to add a space at the end:", filetest. softspace

Example 4 running result:

Whether the file is closed: False file mode: wb file name: file.txt whether to force a space at the end: 0

Close () method
The close () method of the File object refreshes any unwritten information in the buffer and closes the File, so that no data can be written.
When a reference to a file object is re-specified to another file, Python will close the previous file. Close () is a good habit.
Syntax:

fileObject.close();

Example 5

#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/25 # @ Author: wwyxfiletest = open ("file.txt", "wb ") print "Whether the file is closed:", filetest. closedprint "file mode:", filetest. modeprint "file name:", filetest. nameprint "whether to add a space at the end:", filetest. softspaceprint "close the file! "Filetest. close () # close file print" file closed successfully! "

Result 5:

Disable file: False file mode: wb file name: file.txt whether to force a space at the end: 0 to close the file! File closed successfully!

 

5. Read and Write files
File objects provide a series of methods to make file access easier. To see how to use the read () and write () Methods to read and write files.
 Write () method
The write () method canStringWrite an open file. Note that PythonThe string can be binary data.Not just text.
The write () method does not add a line break ('\ n') at the end of the string '):
Syntax:

fileObject.write(string);

Here, the passed parameter is the content to be written to the opened file.
Example 6

#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/25 # @ Author: wwyxfiletest = open ("file.txt", "wb ") filetest. write ("python programming language can be used in many places") print "close the file! "Filetest. close () # close file print" file closed successfully! "Print" re-open the file! "Filetest = open (" file.txt "," rb ") strs = filetest. read (1024) print" File Content: ", strs

Example 6 running result:

Close the file! File closed successfully! Open the file again! My file content is: python programming language can be used in many places

Read () method
The read () method reads a string from an open file. It is important to note that Python strings can be binary data rather than text.
Syntax:

fileObject.read([count])

Here, the passed parameter is the byte count to be read from the opened file. This method is read from the beginning of the file. If count is not input, it will try to read as much content as possible, probably until the end of the file.


Example 6

 

6 File Location

  • The tell () method tells you the current position in the file. In other words, the next read/write will happen after the beginning of the file so many bytes.
  • The seek (offset [, from]) method changes the location of the current file. The Offset variable indicates the number of bytes to be moved. The From variable specifies the reference position for starting to move bytes.
  • If from is set to 0, it means that the start of the file is used as the reference location for moving byte. If it is set to 1, the current location is used as the reference location. If it is set to 2, the end of the file will be used as the reference location.

Example 7:

#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/25 # @ Author: wwyxfiletest = open ("file.txt", "wb ") filetest. write ("python programming language can be used in many places") # open the file filetest = open ("file.txt", "rb") strs = filetest. read (10) print "File Content:", strs # locate the file location p = filetest. tell () print "current file location", p # reset the File Read location filetest. seek (0, 0) print "File Location reset successfully !!! "Print" the File read After resetting the pointer location "strs = filetest. read (10) print" the file content is: ", strsprint" close the file! "Filetest. close () # close file print" file closed successfully! "

Example 7 running result:

The file content is: the current position of the python file is 10. The file location is reset successfully !!! The file content read After resetting the pointer position is: Close the file in python! File closed successfully!

 

7. Rename and delete files
The Python OS module provides methods to help you perform file processing operations, such as renaming and deleting files.
To use this module, you must first import it before calling related functions.
 Rename () method:
The rename () method requires two parameters: the current file name and the new file name.
Syntax:

os.rename(current_file_name, new_file_name)

Example 8:

#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/25 # @ Author: wwyximport osfiletest = open ("myfile.txt", "wb ") # filetest. write ("python basic learning") # disabled after annual check! Filetest. close () # rename the OS file. rename ("myfile.txt", "renamefile.txt") print "the renamed file name is:", filetest. name # open the renamed file fileremane = open ("renamefile.txt", "r") strs = fileremane in read-only mode. read (100) print "file name:", fileremane. nameprint "the content of the modified file after reading is:", strs

Example 8 running result:

The renamed file name is myfile.txt.
File Name: renamefile.txt
The content of the modified file is: python Basics

Note: If the relevant name file already exists under the directory, an exception occurs when you rename the file.

Remove () method
You can use the remove () method to delete a file. You need to provide the file name to be deleted as a parameter.
Syntax:

os.remove(file_name)

Example 9

#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/25 # @ Author: wwyximport osfiletest = open ("myfile.txt", "wb ") # filetest. write ("python basic learning") # disabled after annual check! Filetest. close () # delete the file OS. remove ("myfile.txt") # re-read the deleted file filetest = open ("myfile.txt", "rb") # print the file content print "the file content is:", filetest. read (10)

Example 9 running result

Traceback (most recent call last):  File "E:/python/hello/untitled3/filetest.py", line 14, in <module>    filetest = open("myfile.txt", "rb")IOError: [Errno 2] No such file or directory: 'myfile.txt'

Running result: An exception is reported because a deleted file is read.

 

8. Directory in Python
All files are included in different directories, but Python can easily process them. The OS module has many ways to help you create, delete, and change directories.
Mkdir () method
You can use the mkdir () method of the OS module to create new directories in the current directory. You need to provide a parameter that contains the name of the directory to be created.
Syntax:

os.mkdir("newdir")

 

 Chdir () method
You can use the chdir () method to change the current directory and directory path. A parameter required by the chdir () method is the Directory Name of the current directory.
Syntax:

os.chdir("newdir")

 

Getcwd () method
The getcwd () method displays the current working directory.
Syntax:

os.getcwd()

Rmdir () method
Delete the directory by using the rmdir () method. The directory name is passed as a parameter.
Before deleting this directory, all its contents should be cleared first.
Syntax:

os.rmdir('dirname')

Example 10:

#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Time: 2016/9/25 # @ Author: wwyximport OS # create a directory OS. mkdir ("mydir") # obtain the current directory nowdir = OS. getcwd () print "Current Directory:", nowdir # locate the Directory and modify the directory path OS. chdir ("mydir") # obtain the modified directory path updatedir = OS. getcwd () print "the modified current directory is:", updatedirind = updatedir. rfind ("\") print "truncated string", indprint "type:", type (updatedir) newdir = updatedir [0: int (ind)] print "new dir", newdir # locate the Directory and modify the directory path OS. chdir (newdir) # obtain the modified directory path updatedir = OS. getcwd () print "the modified current directory is:", updatedir # Delete the directory OS. rmdir ("mydir") # obtain the deleted directory path deletedir = OS. getcwd () print "the modified current directory is:", deletedir

Example 10 running result:

The current directory: E: \ python \ hello \ untitled3. The modified current directory is: E: \ python \ hello \ untitled3 \ mydir. The intercepted string 25 type: <type 'str'> the current directory modified by new dir E: \ python \ hello \ untitled3 is: E: \ python \ hello \ untitled3. The modified directory is: E: \ python \ hello \ untitled3

 

9. file and directory related methods
Three important methods can be used to extensively and practically process and manipulate files and directories on Windows and Unix operating systems, as follows:

  • File object method: The file object provides a series of methods for operating files.
  • OS object method: provides a series of methods to process files and directories.

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.