Python Learning Note Nine: file I/O

Source: Internet
Author: User

Print to screen:

1 # !/usr/bin/python 2  3 Print " Python is really a great language, " " isn ' t it? ";

Read keyboard input:

    • Raw_input
    • Input
1 # !/usr/bin/python 2  3 str = raw_input (""); 4 Print "  ", str

Input assumes that your input is a valid Python expression and returns the result of the operation.

1 # !/usr/bin/python 2  3 str = input (""); 4 Print "  ", str
 for  in range (2,10,2 are:  [10, 20, 30, 40]

To open and close a file:

Open function: File object = open (File_name,[,access_mode][,buffering])

    • The File_name:file_name variable is a string value that contains the name of the file you want to access.
    • Access_mode:access_mode determines the mode of opening the file: read-only, write, append, etc. All the desirable values are shown in the full list below. This parameter is non-mandatory and the default file access mode is read-only (R).
    • Buffering: If the value of buffering is set to 0, there is no deposit. If the value of buffering is 1, the row is stored when the file is accessed. If you set the value of buffering to an integer greater than 1, it indicates that this is the buffer size of the storage area. If a negative value is taken, the buffer size of the storage area is the system default.
    • Full list of open files in different modes:
Mode Description
R Open the file as read-only. The pointer to the file will be placed at the beginning of the file. This is the default mode.
Rb Opens a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode.
r+ Open a file for read-write. The file pointer will be placed at the beginning of the file.
rb+ Opens a file in binary format for read-write. The file pointer will be placed at the beginning of the file.
W Open a file for writing only. Overwrite the file if it already exists. If the file does not exist, create a new file.
Wb Open a file in binary format only for writing. Overwrite the file if it already exists. If the file does not exist, create a new file.
w+ Open a file for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file.
wb+ Opens a file in binary format for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file.
A Opens a file for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file to write to.
Ab Opens a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file to write to.
A + Open a file for read-write. If the file already exists, the file pointer will be placed at the end of the file. The file opens with an append mode. If the file does not exist, create a new file to read and write.
ab+ Opens a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file to read and write.
Properties of the File object

After a file is opened, you have a files object that you can get various information about the file.

The following is a list of all properties related to the file object:

Properties Description
File.closed Returns true if the file has been closed, otherwise false is returned.
File.mode Returns the access mode of the file being opened.
File.name Returns the name of the file.
File.softspace If the print output must be followed by a space character, false is returned. Otherwise, returns True.
1 #Coding=utf-82 #!/usr/bin/python3  4 #Open a file5FO = open ("foo.txt","WB")6 Print "Name of the file:", Fo.name7 Print "Closed or not:", fo.closed8 Print "Opening mode:", Fo.mode9 Print "softspace flag:", Fo.softspace
Name of the file:   or  not  :  Falseopening mode:  wbsoftspace flag:  0
Write () method

The write () method writes any string to an open file

1 #Coding=utf-82 #!/usr/bin/python3  4 #Open a file5FO = open ("/tmp/foo.txt","WB")6Fo.write ("Python is a great language.\nyeah its great!! \ n");7  8 #Close an open file9Fo.close ()
Read () method

Reads a string from an open file.

1 #Coding=utf-82 #!/usr/bin/python3  4 #Open a file5FO = open ("/tmp/foo.txt","r+")6str = Fo.read (10);7 Print "Read String is:", str8 #Close an open file9Fo.close ()

File Location:

The tell () method tells you the current position within the file, in other words, the next read and write occurs after so many bytes at the beginning of the file:

The Seek (offset [, from]) method changes the position of the current file. The offset variable represents the number of bytes to move. The from variable specifies the reference position at which to begin moving bytes.

If from is set to 0, this means that the beginning of the file is used as the reference location for moving bytes. If set to 1, the current position is used as the reference location. If it is set to 2, then the end of the file will be used as the reference location.

1 #Coding=utf-82 #!/usr/bin/python3  4 #Open a file5FO = open ("/tmp/foo.txt","r+")6str = Fo.read (10);7 Print "Read String is:", str8  9 #Find Current LocationTenPosition =Fo.tell (); One Print "Current file Position:", Position A   - #Reposition The pointer again to the beginning of the file -Position =fo.seek (0, 0); thestr = Fo.read (10); - Print "Again Read String is:", str - #Close an open file -Fo.close ()
Renaming and deleting files
 1  #   2  #  !/usr/bin/python  3  import   OS  4  5  #   Rename the file Test1.txt to Test2.txt.  6  os.rename ( " test1.txt  , "  test2.txt  ) 
1 # Coding=utf-8 2 # !/usr/bin/python 3 Import OS 4  5 # Delete a file that already exists Test2.txt 6 os.remove ("text2.txt")
mkdir () method

You can use the mkdir () method of the OS module to create new catalogs in the current directory.

1 # Coding=utf-8 2 # !/usr/bin/python 3 Import OS 4  5 # Create catalog Test 6 Os.mkdir ("test")
ChDir () method

You can use the ChDir () method to change the current directory.

1 # Coding=utf-8 2 # !/usr/bin/python 3 Import OS 4  5 # change the current directory to "/home/newdir" 6 Os.chdir ("/home/newdir")

GETCWD () Method:

The GETCWD () method displays the current working directory.

1 # Coding=utf-8 2 # !/usr/bin/python 3 Import OS 4  5 # give the current directory 6 OS.GETCWD ()
RmDir () method

The RmDir () method deletes the directory, and the directory name is passed as a parameter.

#coding =utf-8#!/usr/bin/pythonimport OS # delete "/tmp/test" directory Os.rmdir ("/tmp/test"  )
1 # Coding=utf-8 2 # !/usr/bin/python 3 Import OS 4  5 # Delete the "/tmp/test" directory 6 " /tmp/test "  )

Python Learning Note Nine: file I/O

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.