Python file I/O

Source: Internet
Author: User

Python file I/O
Python file I/O

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

Print to 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:

#! /Usr/bin/python #-*-coding: UTF-8-*-print "Python is a great language, isn't it? ";

The following results are generated on your standard screen:

Python is a great language, isn't it?
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
  • Inputraw_input Function

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

    #!/usr/bin/python str = raw_input("Enter your input: ");print "Received input is : ", str

    This will prompt you to enter any string and display the same string on the screen. When I enter "Hello Python! ", Its output is as follows:

    Enter your input: Hello PythonReceived input is :  Hello Python
    Input Function

    The input ([prompt]) function and raw_input ([prompt]) function are basically interchangeable, but the input assumes that your input is a valid Python expression and returns the calculation result.

    #!/usr/bin/python str = input("Enter your input: ");print "Received input is : ", str

    This will generate the following results corresponding to the input:

    Enter your input: [x*5 for x in range(2,10,2)]Recieved input is :  [10, 20, 30, 40]
    Open and Close files

    Up to now, you can read and write data to standard input and input. 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 first use the Python built-in open () function to open a file and create a file object. The related auxiliary methods can call it for read and 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, append, and so on. 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, there will be no storage. 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
      R Open the file in read-only mode. The file pointer will be placed at the beginning of the file. This is the default mode.
      Rb Open 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 reading and writing. The file pointer will be placed at the beginning of the file.
      Rb + Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file.
      W Open a file for writing only. If the file already exists, overwrite it. If the file does not exist, create a new file.
      Wb Open a file in binary format for writing only. If the file already exists, overwrite it. If the file does not exist, create a new file.
      W + Open a file for reading and writing. If the file already exists, overwrite it. If the file does not exist, create a new file.
      Wb + Open a file in binary format for reading and writing. If the file already exists, overwrite it. If the file does not exist, create a new file.
      A Open a file for append. If the file already exists, the file pointer is placed at the end of the file. That is to say, the new content will be written to the existing content. If the file does not exist, create a new file for writing.
      AB Open a file in binary format for append. If the file already exists, the file pointer is placed at the end of the file. That is to say, the new content will be written to the existing content. If the file does not exist, create a new file for writing.
      A + Open a file for reading and writing. If the file already exists, the file pointer is placed at the end of the file. When the file is opened, the append mode is used. If the file does not exist, create a new file for reading and writing.
      AB + Open a file in binary format for append. If the file already exists, the file pointer is placed at the end of the file. If the file does not exist, create a new file for reading and writing.
      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. closed Returns true if the object is closed; otherwise, returns false.
      File. mode Returns the access mode of the opened file.
      File. name The name of the returned file.
      File. softspace If the print output must be followed by a space character, false is returned. Otherwise, true is returned.

      Example:

      #! /Usr/bin/python #-*-coding: UTF-8-*-# open a file fo = open ("foo.txt", "wb") print "Name of the file: ", fo. nameprint "Closed or not:", fo. closedprint "Opening mode:", fo. modeprint "Softspace flag:", fo. softspace

      Output result of the above instance:

      Name of the file:  foo.txtClosed or not :  FalseOpening mode :  wbSoftspace flag :  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:

      #! /Usr/bin/python #-*-coding: UTF-8-*-# open a file fo = open ("foo.txt", "wb") print "Name of the file: ", fo. name # Close the open file fo. close ()

      Output result of the above instance:

      Name of the file:  foo.txt

      Read/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 can Write any string into an open file. It is important to note that Python strings can be binary data rather than text.

      The Write () method does not end with a string and does not add a line break ('\ n '):

      Syntax:

      fileObject.write(string);

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

      Example:

      #! /Usr/bin/python #-*-coding: UTF-8-*-# open a file fo = open ("/tmp/foo.txt", "wb") fo. write ("Python is a great language. \ nYeah its great !! \ N "); # close the open file fo. close ()

      The preceding statement creates the foo.txt file, writes the received content to the file, and closes the file. If you open this file, you will see the following:

      Python is a great language.Yeah its great!!
      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:

      Use the foo.txt file created in our workshop.

      #! /Usr/bin/python #-*-coding: UTF-8-*-# open a file fo = open ("/tmp/foo.txt", "r +") str = fo. read (10); print "Read String is:", str # Close open file fo. close ()

      Output result of the above instance:

      Read String is :  Python is

      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:

      Use the foo.txt file created in our workshop.

      #! /Usr/bin/python #-*-coding: UTF-8-*-# open a file fo = open ("/tmp/foo.txt", "r +") str = fo. read (10); print "Read String is:", str # Find the current position = fo. tell (); print "Current file position:", position # re-locate the pointer to the beginning of the file position = fo. seek (0, 0); str = fo. read (10); print "Again read String is:", str # Close open file fo. close ()

      Output result of the above instance:

      Read String is :  Python isCurrent file position :  10Again read String is :  Python is
      Rename and delete objects

      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 and then call 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:

      In the following example, a file test1.txt already exists.

      #! /Usr/bin/python #-*-coding: UTF-8-*-import OS # rename file test1.txtto test2.txt. OS. rename ("test1.txt", "test2.txt ")
      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:

      In the following example, a file test2.txt already exists will be deleted.

      #! /Usr/bin/python #-*-coding: UTF-8-*-import OS # delete an existing file test2.txt OS. remove ("test2.txt ")
      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")

      Example:

      In the following example, a new directory named test is created under the current directory.

      #! /Usr/bin/python #-*-coding: UTF-8-*-import OS # create directory testos. mkdir ("test ")
      Chdir () method

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

      Syntax:

      os.chdir("newdir")

      Example:

      The following example will go to the "/home/newdir" directory.

      #! /Usr/bin/python #-*-coding: UTF-8-*-import OS # change the current directory to "/home/newdir" OS. chdir ("/home/newdir ")

      Getcwd () method:

      The getcwd () method displays the current working directory.

      Syntax:

      os.getcwd()

      Example:

      The following example shows the current directory:

      #! /Usr/bin/python #-*-coding: UTF-8-*-import OS # Give the current directory 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:

      The following is an example of deleting the "/tmp/test" directory. The full compliance name of the directory must be given; otherwise, the directory will be searched in the current directory.

      #! /Usr/bin/python #-*-coding: UTF-8-*-import OS # Delete "/tmp/test" directory OS. rmdir ("/tmp/test ")
      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.

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.