Daydayup_python self-study record [8]_ file I/O

Source: Internet
Author: User

Python file I/O

This chapter only covers all the basic I/O functions, and more functions refer to the Python standard documentation.
Print to screen
The simplest way to output this is to use the print statement, which you can pass 0 or more comma-separated expressions. This function converts the expression you pass to a string expression and writes the result to the standard output as follows:

#!/usr/bin/python# -*- coding: UTF-8 -*- print "Python 是一个非常棒的语言,不是吗?";
Reading keyboard input

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

    • Raw_input
    • Input

    • Raw_input function

The Raw_input ([prompt]) function reads a line from the standard input and returns a string (minus the end of the newline character):

#!/usr/bin/python# -*- coding: UTF-8 -*- str = raw_input("请输入:""你输入的内容是: ", str
    • Input function

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

#!/usr/bin/python# -*- coding: UTF-8 -*- str = input("请输入:""你输入的内容是: ", str这会产生如下的对应着输入的结果:请输入:[x*5forin range(2,10,2)]你输入的内容是:  [10203040]

Note: the range () function

>>> range(1,5#代表从1到5(不包含5)[1234]>>> range(1,5,2#代表从1到5,间隔2(不包含5)[13]>>> range(5#代表从0到5(不包含5)[01234]
Opening and closing files

You can now read and write to standard input and output. Now, let's see how to read and write actual data files.
Python provides the necessary functions and methods for basic file operation by default. You can use the file object to do most of the document operations.

Open function

You must first open a file with the Python built-in open () function, create a Document object, and the related method can call it for read and write.
Grammar:

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

The details of each parameter are as follows:
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:

模式  描述r   以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。rb  以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。r+  打开一个文件用于读写。文件指针将会放在文件的开头。rb+ 以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。w   打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。wb  以二进制格式打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。w+  打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。wb+ 以二进制格式打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。a   打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。ab  以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。a+  打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。ab+ 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。

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:

属性  描述file.closed 返回true如果文件已被关闭,否则返回false。file.mode   返回被打开文件的访问模式。file.name   返回文件的名称。file.softspace  如果用print输出后,必须跟一个空格符,则返回false。否则返回true。

The following example:

#!/usr/bin/python# -*- coding: UTF-8 -*-# 打开一个文件open("foo.txt""wb")print"文件名: ", fo.nameprint"是否已关闭 : ", fo.closedprint"访问模式 : ", fo.modeprint"末尾是否强制加空格 : ", fo.softspace
Close () method

The close () method of the file object flushes any information that has not yet been written in the buffer and closes the file, which can no longer be written.
When a reference to a file object is re-assigned to another file, Python closes the previous file. Closing a file with the close () method is a good habit.
Grammar:
Fileobject.close ();

Read and Write files:

The file object provides a series of methods that make it easier to access our files. Take a look at how to read and write to the file using the read () and write () methods.

Write () method

The write () method writes any string to an open file. It is important to note that the Python string can be binary data, not just text.
The Write () method does not add a line break (' \ n ') at the end of the string:
Grammar:
Fileobject.write (string);
Here, the parameter being passed is the content to be written to the open file.
Example:

#!/usr/bin/python# -*- coding: UTF-8 -*-# 打开一个文件fo = open("foo.txt""wb""www.runoob.com!\nVery good site!\n");# 关闭打开的文件fo.close()

The above method creates a Foo.txt file, writes the received content to the file, and eventually closes the file

Read () method

The Read () method reads a string from an open file. It is important to note that the Python string can be binary data, not just text.
Grammar:
Fileobject.read ([count]);
Here, the parameter being passed is the count of bytes to read from the open file. The method reads in from the beginning of the file, and if it does not pass in count, it tries to read as much more content as possible, most likely until the end of the file.
Example:
Here we use the Foo.txt file created above.

#!/usr/bin/python# -*- coding: UTF-8 -*-# 打开一个文件fo = open("foo.txt""r+")str = fo.read(10"读取的字符串是 : ", str# 关闭打开的文件fo.close()
File Location: File locator

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.
Example:
Just use the file Foo.txt we created above.

#!/usr/bin/python#-*-Coding:utf-8-*-# Open a fileFO =Open("Foo.txt","r+") str = fo.Read(Ten);Print "The string read is:"Str# Find the current locationPosition = fo. Tell();Print "Current file location:", Position# Reposition the pointer again to the beginning of the filePosition = fo.Seek(0,0); str = fo.Read(Ten);Print "re-reading string:"Str# Close open filesFo.Close()
Renaming and deleting files

Python's OS module provides a way to help you perform file processing operations, such as renaming and deleting files.
To use this module, you must first import it before you can invoke the various functions associated with it.
Rename () Method:
The rename () method requires two parameters, the current file name, and a new filename.
Grammar:

os.rename(current_file_name, new_file_name)

Example:
The following example renames a file that already exists test1.txt.

#!/usr/bin/python# -*- coding: UTF-8 -*-import os# 重命名文件test1.txt到test2.txt。"test1.txt""test2.txt" )
Remove () method

You can delete the file using the Remove () method, and you need to provide the filename to delete as a parameter.
Grammar:

os.remove(file_name)

Example:
The following example deletes a file that already exists test2.txt.

#!/usr/bin/python# -*- coding: UTF-8 -*-import os# 删除一个已经存在的文件test2.txtos.remove("test2.txt")Python里的目录:

All files are contained in different directories, but Python is also easy to handle. 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 catalogs in the current directory. You need to provide a parameter that contains the name of the directory you want to create.
Grammar:

os.mkdir("newdir")

Example:
The following example creates a new catalog test under the current directory.

#!/usr/bin/python# -*- coding: UTF-8 -*-import os# 创建目录testos.mkdir("test")
ChDir () method

You can use the ChDir () method to change the current directory. The ChDir () method requires a parameter that you want to set as the directory name of the current directory.
Grammar:

os.chdir("newdir")

Example:
The following example goes to the "/home/newdir" directory.

#!/usr/bin/python# -*- coding: UTF-8 -*-import os# 将当前目录改为"/home/newdir"os.chdir("/home/newdir")

GETCWD () Method:
The GETCWD () method displays the current working directory.
Grammar:

os.getcwd()
RmDir () method

The RmDir () method deletes the directory, and the directory name is passed as a parameter.
Before deleting this directory, all of its contents should be purged first.
Grammar:

os.rmdir(‘dirname‘)

Example:
The following is an example of deleting the "/tmp/test" directory. The fully compliant name of the directory must be given, otherwise the directory will be searched under the current directory.

#!/usr/bin/python# -*- coding: UTF-8 -*-import os# 删除”/tmp/test”目录"/tmp/test"  )

File, directory-related methods
Three important method sources can be used for a wide and practical processing and manipulation of files and directories on Windows and UNIX operating systems, as follows:

    • File Object method: The File object provides a series of methods for manipulating files.
    • OS Object methods: Provides a series of methods for working with files and directories.
Python file (file) method

The file object is created using the Open function, and the following table lists the functions commonly used by file objects:

Serial Number Method Description
1 File.close () Close the file. File can no longer read and write after closing
2 File.flush () Refreshes the file internal buffer, directly writes the internal buffer data immediately to the file, rather than passively waits for the output buffer to write.
3 File.fileno () Returns an integer that is a file descriptor (Descriptor FD Integer) that can be used in some of the underlying operations, such as the Read method of the OS module.
4 File.isatty () Returns True if the file is connected to an end device, otherwise False is returned.
5 File.next () Returns the next line of the file.
6 File.read ([size]) Reads the specified number of bytes from the file, if none is given or is negative.
7 File.readline ([size]) Reads the entire line, including the "\ n" character.
8 File.readlines ([Sizehint]) Reads all rows and returns a list, and if given sizeint>0, returns a row with a sum of approximately sizeint bytes, the actual read value may be larger than sizhint because the buffer needs to be populated.
9 File.seek (offset[, whence]) Set the current location of the file
10 File.tell () Returns the current location of the file.
11 File.truncate ([size]) Intercepts the file, the truncated byte is specified by size, and the default is the current file location.
12 File.write (str) Writes a string to the file without a return value.
13 File.writelines (Sequence) Writes a list of sequence strings to the file and adds a newline character to each line if a line break is required.

"'

Daydayup_python self-study record [8]_ file I/O

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.