Detailed introduction to file I/O operations in Python

Source: Internet
Author: User

Detailed introduction to file I/O operations in Python

This article mainly introduces file I/O operations in Python, which is the basic knowledge in getting started with Python. For more information, see

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:

?

1

2

3

#! /Usr/bin/python

 

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

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

?

1

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 ).

?

1

2

3

4

#! /Usr/bin/python

 

Str = 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:

?

1

2

Enter your input: Hello Python

Written ed 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.

?

1

2

3

4

#! /Usr/bin/python

 

Str = input ("Enter your input :");

Print "Received input is:", str

For the input, the result is as follows:

?

1

2

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:

?

1

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:

?

1

2

3

4

5

6

7

8

#! /Usr/bin/python

 

# Open a file

Fo = open ("foo.txt", "wb ")

Print "Name of the file:", fo. name

Print "Closed or not:", fo. closed

Print "Opening mode:", fo. mode

Print "Softspace flag:", fo. softspace

This produces the following results:

?

1

2

3

4

Name of the file: foo.txt

Closed or not: False

Opening mode: wb

Softspace 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:

?

1

FileObject. close ();

Example:

?

1

2

3

4

5

6

7

8

#! /Usr/bin/python

 

# Open a file

Fo = open ("foo.txt", "wb ")

Print "Name of the file:", fo. name

 

# Close opend file

Fo. close ()

This produces the following results:

?

1

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:

?

1

FileObject. write (string );

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

Example

?

1

2

3

4

5

6

7

8

#! /Usr/bin/python

 

# Open a file

Fo = open ("foo.txt", "wb ")

Fo. write ("Python is a great language. \ nYeah its great !! \ N ");

 

# Close opend file

Fo. close ()

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

?

1

2

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

?

1

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.

?

1

2

3

4

5

6

7

8

#! /Usr/bin/python

 

# Open a file

Fo = open ("foo.txt", "r + ")

Str = fo. read (10 );

Print "Read String is:", str

# Close opend file

Fo. close ()

This produces the following results:

?

1

Read String is: Python is

File Location:

The tell () method tells the current location of the file. In other words, 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.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

#! /Usr/bin/python

 

# Open a file

Fo = open ("foo.txt", "r + ")

Str = fo. read (10 );

Print "Read String is:", str

 

# Check current position

Position = fo. tell ();

Print "Current file position:", position

 

# Reposition pointer at the beginning once again

Position = fo. seek (0, 0 );

Str = fo. read (10 );

Print "Again read String is:", str

# Close opend file

Fo. close ()

This produces the following results:

?

1

2

3

Read String is: Python is

Current file position: 10

Again 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:

?

1

OS. rename (current_file_name, new_file_name)

Example

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

?

1

2

3

4

5

#! /Usr/bin/python

Import OS

 

# Rename a file from test1.txt to test2.txt

OS. 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:

?

1

OS. remove (file_name)

Example

The following example deletes the test2.txt file:

?

1

2

3

4

5

#! /Usr/bin/python

Import OS

 

# Delete file test2.txt

OS. 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:

?

1

OS. mkdir ("newdir ")

Example:

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

?

1

2

3

4

5

#! /Usr/bin/python

Import 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:

?

1

OS. chdir ("newdir ")

Example:

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

?

1

2

3

4

5

#! /Usr/bin/python

Import OS

 

# Changing a directory to "/home/newdir"

OS. chdir ("/home/newdir ")

Getcwd () method:

The getcwd () method displays the current working directory.

Example:

?

1

OS. getcwd ()

Example:

The following example is used to specify the current directory:

?

1

2

3

4

5

#! /Usr/bin/python

Import OS

 

# This wowould give location of the current directory

OS. 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:

?

1

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.

?

1

2

3

4

5

#! /Usr/bin/python

Import OS

 

# This woshould remove "/tmp/test" directory.

OS. rmdir ("/tmp/test ")

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.