Describes in detail the file I/O operations in Python,

Source: Internet
Author: User

Describes in detail the file I/O operations in Python,

This chapter covers all basic I/O functions used in Python. For more functions, see the standard Python documentation.
Print to the screen:

The simplest way to generate an output is to use the print statement. You can use zero or multiple expressions separated by commas. This function is passed to a string expression and the result is written to the standard output, as shown below:

#!/usr/bin/pythonprint "Python is really a great language,", "isn't it?";

This outputs the result on the standard screen. The result is as follows:

Python is really a great language, isn't it?

Read keyboard input:

Python provides two built-in functions to read a row from the standard input, which is the text from the keyboard by default. These functions include:

  • Raw_input
  • Input

Raw_input function:

Raw_input ([prompt]) function reads a row from the standard input and returns a string (remove the ending line feed ).

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

This will prompt you to enter a string that will display the same string on the screen. When "Hello Python!" Is input !", Its output is as follows:

Enter your input: Hello PythonReceived input is : Hello Python

Input Function:

The input ([prompt]) function is equivalent to raw_input, But it assumes that the input is a valid Python expression and returns the calculation result.

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

For the input, the result is as follows:

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, we have learned how to read and write standard inputs and outputs. Now let's look at how to use actual data files.

Python provides basic functions and methods to operate files by default. You can use a file object to perform most file operations.
Open function:

To read or write files, you must use the Python built-in open () function to open the file. This function creates a file object, which is used to call other supported methods associated with it.
Syntax:

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

The following is the detailed information about the parameters:

  • File_name: The file_name parameter is a string value that contains the name of the file to be accessed.
  • Access_mode: access_mode determines that the file must be opened, that is, the possible values of read, write, and append are a complete list mode given in the following table. This is an optional parameter. The default file access method is read (r ).
  • Buffering: If the buffer value is set to 0, no buffer will occur. If the buffer value is 1, the row buffer accesses a file for execution. If the specified buffer value is an integer greater than 1, the buffer is used with the specified buffer size. If it is negative, the buffer size is the system default (default behavior ).

Here is a list of different modes for opening a file:

File object attributes:

Once a file is opened, the file object can obtain various information about the file.

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

Example:

#!/usr/bin/python# Open a filefo = open("foo.txt", "wb")print "Name of the file: ", fo.nameprint "Closed or not : ", fo.closedprint "Opening mode : ", fo.modeprint "Softspace flag : ", fo.softspace

This produces the following results:

Name of the file: foo.txtClosed or not : FalseOpening mode : wbSoftspace flag : 0

Close () method:

The close () method of a file object refreshes the unwritten information and closes the object of the file. After that, no data content can be written.

Python is automatically disabled when the referenced object of the file is reassigned to another file. It is a good practice to close a file using the close () method.
Syntax:

fileObject.close();

Example:

#!/usr/bin/python# Open a filefo = open("foo.txt", "wb")print "Name of the file: ", fo.name# Close opend filefo.close()

This produces the following results:

Name of the file: foo.txt

Read and Write files:

The file object provides a set of access methods. Let's take a look at how to use the read () and write () Methods to read and write files.
Write () method:

The write () method writes a string to any open file. Note that Python strings can have binary data, not just text.

Do not add the newline character ('\ n') to the end of the string in the write () method:
Syntax:

fileObject.write(string);

Here, the passed parameter is the content of the file to be written to open.
Example

#!/usr/bin/python# Open a filefo = open("foo.txt", "wb")fo.write( "Python is a great language.\nYeah its great!!\n");# Close opend filefo.close()

The above method will create the foo.txt file, write the given content in the file, and eventually close the file.

Python is a great language.Yeah its great!!

Read () method:

Read () method to read the string of an opened file. Note that Python strings can have binary data, not just text.
Syntax

fileObject.read([count]);

Here, the passed parameter is the number of bytes read from the opened file. This method reads from the beginning of the file. If the count is lost, it tries to read as many as possible until the end of the file.
Example:

Here we use a file foo.txt as an example, which is created on the above.

#!/usr/bin/python# Open a filefo = open("foo.txt", "r+")str = fo.read(10);print "Read String is : ", str# Close opend filefo.close()

This produces the following results:

Read String is : Python is

File Location:

Tell () methodIndicates the current location of the file. In other words, the number of bytes that the next read or write will occur at the beginning of the file.

The seek (offset [, from]) method changes the current file location. The offset parameter indicates the number of bytes to be moved. The specified byte from this parameter will be moved to the reference point.

If from is set to 0, this means that the start of the file is used as the reference position. If it is set to 1, the current position is used as the reference position. If it is set to 2, the end of the file will be used as the reference position.
Example

Let's use a file foo.txt, which is created above.

#!/usr/bin/python# Open a filefo = open("foo.txt", "r+")str = fo.read(10);print "Read String is : ", str# Check current positionposition = fo.tell();print "Current file position : ", position# Reposition pointer at the beginning once againposition = fo.seek(0, 0);str = fo.read(10);print "Again read String is : ", str# Close opend filefo.close()

This produces the following results:

Read String is : Python isCurrent file position : 10Again read String is : Python is

Rename and delete files:

The Python OS module provides some 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 the relevant functions.
Rename () method:

The rename () method has two parameters: the current file name and the new file name.
Syntax:

os.rename(current_file_name, new_file_name)

Example

The following example is used to rename the test1.txt file:

#!/usr/bin/pythonimport os# Rename a file from test1.txt to test2.txtos.rename( "test1.txt", "test2.txt" )

Remove () method:

You can use the remove () method to provide parameters as the file name as the file to be deleted.
Syntax:

os.remove(file_name)

Example

The following example deletes the test2.txt file:

#!/usr/bin/pythonimport os# Delete file test2.txtos.remove("text2.txt")

Directory in Python:

All files contain different directories, but there is no problem in Python. The OS module can be used to create, delete, and change directories.
Mkdir () method:

You can use the mkdir () method of the OS module to create a directory under the current directory. You need to provide parameters. This method contains the name of the directory to be created.
Syntax:

os.mkdir("newdir")

Example:

The following example shows how to create the test directory in the current directory:

#!/usr/bin/pythonimport os# Create a directory "test"os.mkdir("test")

Chdir () method:

You can use the chdir () method to change the current directory. The chdir () method accepts a parameter, that is, the name of the directory of the current directory.
Syntax:

os.chdir("newdir")

Example:

The following is an example of accessing the "/home/newdir" directory:

#!/usr/bin/pythonimport os# Changing a directory to "/home/newdir"os.chdir("/home/newdir")

Getcwd () method:

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

os.getcwd()

Example:

The following example is used to specify the current directory:

#!/usr/bin/pythonimport os# This would give location of the current directoryos.getcwd()

Rmdir () method:

Rmdir () command to delete a directory, which is a parameter of the method.

When deleting a directory, all its contents should be deleted.
Syntax:

os.rmdir('dirname')

Example

The following is an example to delete the "/tmp/test" directory. It is required to obtain the full name of the directory. Otherwise, the directory in the current directory will be searched.

#!/usr/bin/pythonimport os# This would remove "/tmp/test" directory.os.rmdir( "/tmp/test" )

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.