Latest web development tutorials

Python file I / O

This chapter only describes all the basic I / O functions, more functions please refer to the Python standard documentation.

Print to Screen

The easiest method is to use print statement output, you can pass it zero or more expressions separated by commas. This function converts the expression you pass a string expression, and the result is written to standard output as follows:

#!/usr/bin/python
# -*- coding: UTF-8 -*- 

print "Python 是一个非常棒的语言,不是吗?";

Will produce the following results on your standard screen:

Python 是一个非常棒的语言,不是吗?

Read keyboard input

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

  • raw_input
  • input

raw_input function

raw_input ([prompt]) function to read a line from standard input, and returns a string (trailing newline removed):

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

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

请输入:Hello Python!
你输入的内容是:  Hello Python!

input function

input ([prompt]) function and raw_input ([prompt]) function substantially similar, but input can receive a Python expression as input and returns the result of the operation.

#!/usr/bin/python
# -*- coding: UTF-8 -*- 
 
str = input("请输入:");
print "你输入的内容是: ", str

This produces the following results corresponding to the input:

请输入:[x*5 for x in range(2,10,2)]
你输入的内容是:  [10, 20, 30, 40]

Opening and Closing Files

You are now able to read and write to the standard input and output. Now, take a look at how to read and write the actual data files.

Python provides the necessary functions and methods for file default of the basic operation. You can use thefile objects do most file operations.

open function

You must use Python's built-in open () function to open a file, create a file object, and related methods can invoke it to read and write.

grammar:

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

Details of the various parameters is as follows:

  • file_name: file_name variable is a string containing the value you want to access a file name.
  • access_mode: access_mode decided to open the file mode: Read, Write, appending. See the complete list of all possible values ​​as follows. This non-mandatory parameter, the default file access mode is read-only (r).
  • buffering: If the value of buffering is set to 0, there will be no storage. If the value of buffering take 1, it will register the line when accessing files. If the value is set buffering integer greater than 1, indicating the size of this buffer is a storage area. If a negative value, the size of the buffer storage zone for the system default.

Open the complete list of the different modes of file:

mode description
r Open the file in read-only mode. Pointer file will be placed at the beginning of the file. This is the default mode.
rb Open a file for read-only in binary format. Will file pointer at the beginning of the file. This is the default mode.
r + Open a file for reading and writing. Will file pointer at the beginning of the file.
rb + Open a file for reading and writing in binary format. Will file pointer at the beginning of the file.
w Open a file for writing only. If the file already exists it will be overwritten. If the file does not exist, create a new file.
wb Open a file for writing in binary format only. If the file already exists it will be overwritten. If the file does not exist, create a new file.
w + Open a file for reading and writing. If the file already exists it will be overwritten. If the file does not exist, create a new file.
wb + Open a file for reading and writing in binary format. If the file already exists it will be overwritten. If the file does not exist, create a new file.
a Open a file for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, after 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 for append in binary format. If the file already exists, the file pointer will be placed at the end of the file. In other words, after 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 will be placed at the end of the file. It will append mode the file is opened. If the file does not exist, create a new file for reading and writing.
ab + Open a file for append in binary format. 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 for reading and writing.

File attributes object

After a file is opened, you have a file object, you can get all kinds of information about the file.

The following is a list of all file attributes and objects related to:

Attributes description
file.closed Returns true if the file has been closed, otherwise it returns false.
file.mode Return to the open file access mode.
file.name Returns the name of the file.
file.softspace If using print output, must be followed by a space character, it returns false. Otherwise, it returns true.

The following examples:

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

Examples of the above output:

文件名:  foo.txt
是否已关闭 :  False
访问模式 :  wb
末尾是否强制加空格 :  0

close () method

close File object () method to refresh any information not write buffer, and close the file, after which they can no longer be written.

When referencing a file object to be re-assigned to another file, Python will close the previous file. With the close () method to close the file is a good habit.

grammar:

fileObject.close();

example:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 打开一个文件
fo = open("foo.txt", "wb")
print "文件名: ", fo.name
 
# 关闭打开的文件
fo.close()

Examples of the above output:

文件名:  foo.txt

Read and write files:

file object provides a number of methods allow us to access files more easily. See how to use read () and write () methods to read and write files.

write () method

write () method to write an open file any string. It is important to note that, Python strings can be binary data, rather than just text.

write () method does not add a newline at the end of the string ( '\ n'):

grammar:

fileObject.write(string);

Here, the parameters are passed is to be written to open the file's contents.

example:

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

The above-described method creates foo.txt file, and writes the contents of the documents received and finally close the file. If you open this file, you will see the following:

$ cat foo.txt 
www.w3big.com!
Very good site!

read () method

read () method reads a string from an open file. It is important to note that, Python strings can be binary data, rather than just text.

grammar:

fileObject.read([count]);

Here, the argument is being passed from the open file byte count read. The method started from the beginning of the file is read, if no incoming count, it will try to read as much more content, probably 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);
print "读取的字符串是 : ", str
# 关闭打开的文件
fo.close()

Examples of the above output:

读取的字符串是 :  www.w3big

File location:


File Location

tell () method tells you the current location within the file; in other words, the next read or write will occur after the beginning of the file so many bytes.

seek (offset [, from]) method to change the location of the current file. Offset variable indicates the number of bytes to be moved. From start to move byte variable specifies the reference position.

If from is set to 0, which means the beginning of the file as the reference position to move bytes. If set to 1, the current position as the reference position. If it is set to 2, then the end of the file will be used as the reference position.

example:

On file with us created above foo.txt.

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 打开一个文件
fo = open("foo.txt", "r+")
str = fo.read(10);
print "读取的字符串是 : ", str
 
# 查找当前位置
position = fo.tell();
print "当前文件位置 : ", position
 
# 把指针再次重新定位到文件开头
position = fo.seek(0, 0);
str = fo.read(10);
print "重新读取字符串 : ", str
# 关闭打开的文件
fo.close()

Examples of the above output:

读取的字符串是 :  www.w3big
当前文件位置 :  10
重新读取字符串 :  www.w3big

Rename and delete files

Python's os module provides to help you perform file processing operation methods, such as renaming and deleting files.

To use this module, you must first import it before you can call the various functions related.

rename () method:

rename () method requires two parameters, the current file name and the new file name.

grammar:

os.rename(current_file_name, new_file_name)

example:

The following example will rename a file that already exists test1.txt.

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os
 
# 重命名文件test1.txt到test2.txt。
os.rename( "test1.txt", "test2.txt" )

remove () method

You can use the remove () method to delete the file, you need to provide the name of the file to be deleted as a parameter.

grammar:

os.remove(file_name)

example:

The following example will delete a file that already exists test2.txt.

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os
 
# 删除一个已经存在的文件test2.txt
os.remove("test2.txt")

Python in the directory:

All files are contained in the various directories, but Python can easily handle. os module There are many ways to help you to create, delete, and change directories.

mkdir () method

You can use the os module mkdir () method creates a new directory are in the current directory. You need to provide a parameter that contains the name of the directory to be created.

grammar:

os.mkdir("newdir")

example:

The following example creates a new directory test in the current directory.

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os
 
# 创建目录test
os.mkdir("test")

chdir () method

You can use chdir () method to change the current directory. A parameter chdir () method requires that you want to set as the directory name of the current directory.

grammar:

os.chdir("newdir")

example:

The following example will enter "/ home / newdir" directory.

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os
 
# 将当前目录改为"/home/newdir"
os.chdir("/home/newdir")

getcwd () method:

getcwd () method to display the current working directory.

grammar:

os.getcwd()

example:

The following example shows the current directory:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os
 
# 给出当前的目录
os.getcwd()

rmdir () method

rmdir () method to delete the directory, the directory name passed as a parameter.

Before deleting this directory and all its contents should be cleared first.

grammar:

os.rmdir('dirname')

example:

The following is deleted "/ tmp / test" directory example. Fully compliant directory name must be given, otherwise it will search the directory in the current directory.

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os
 
# 删除”/tmp/test”目录
os.rmdir( "/tmp/test"  )

Files, directories, related methods

Three methods can be an important source of files and directories on Windows and Unix operating systems perform a wide range of practical handling and manipulation, as follows:

  • File object method : file object provides a series of methods manipulating files.
  • OS Object : providing a method for processing a series of files and directories.