Dowemo
0 0 0 0


This chapter covers all the basic I o functions, and more functions refer to the python standard documentation.

Print to screen

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

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

Your standard screen will produce the following results:

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

Read keyboard input

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

  • Raw_input
  • input

Raw input function

A raw_input ( [ prompt ] ) function reads a row from a standard input and retur & a string ( eliminating the trailing line break ):

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

This prompts you for any string and then displays the same string on the screen. When I enter"hello python"! ", its output is as follows:

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

Input function

Input ( [ prompt ] ) Function and Raw_input ( [ prompt ] ) Function basically similar, but input can receive a python expression as input and return the result of the operation.

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

This produces the result of the following input:

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

Open and close files

Now you can read and write to standard input and output. Now, let's see how to read the actual data files.

Python provides the necessary functio & and methods for default operatio & on files under default. You can do most of the file operations with the .

Open function

You must open a file with the python built-in open ( ) function, creating a file object, and the associated method can call it to read and write it.

Syntax:

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

Details of each parameter are as follows:

  • A file_name: file name variable is a string value that contains the filename you want to access.
  • Access_mode: access mode determines the mode for opening files: write, append, etc. All possible values see the complete list below. This parameter is and the default file access mode is ( R ).
  • Buffering: if the value of buffering is set to 0, there's no register. If the value of buffering is 1, the file will be saved when the file is accessed. If the value of buffering is set to an integer greater than 1, it indicates that the buffer size is. If a negative value is taken, the buffer size is the default.

A full list of open files in different modes:

Pattern description
rOpen a file in mode. The pointer to the file will be placed at the beginning of the file. This is the default mode.
rbOpen a file in binary format for. File pointer will be placed at the beginning of the file. This is the default mode.
R +Open a file for reading and writing. File pointer will be placed at the beginning of the file.
Rb +Open a file in binary format for read/write. File pointer will be placed at the beginning of the file.
wOpen a file for writing only. If the file already exists, overwrite it. If the file doesn't exist, create a new file.
wbOpen a file in binary format only for writing. If the file already exists, overwrite it. If the file doesn't exist, create a new file.
W +Open a file for reading and writing. If the file already exists, overwrite it. If the file doesn't exist, create a new file.
Wb +Open a file in binary format for read/write. If the file already exists, overwrite it. If the file doesn't exist, create a new file.
aOpen a file for append. If the file already exists, the file pointer will be placed at the end of the file. That's, the new content will be written to the existing content. If the file doesn't exist, create a new file.
abOpen a file in binary format for append. If the file already exists, the file pointer will be placed at the end of the file. That's, the new content will be written to the existing content. If the file doesn't exist, create a new file.
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. The file is open when it's opened. If the file doesn't 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 will be placed at the end of the file. If the file doesn't exist, create a new file for reading and writing.

Properties of the file object

After a file is opened, you've a file object that you can get information about the file.

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

Attribute description
File. Closed.Retur true if the file is closed or false.
File. Mode.Return access mode for open files.
File. Name.Returns the name of the file.
File. Softspace.If you use print output, you must go to a space space and return false. Otherwise return true.

The following example:

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

The following example outputs the results:

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

Close ( ) method

The close ( ) method of the file object refreshes any information that isn't written in the buffer, and closes the file, which cannot be written again.

When a reference to a file object is redefined to another file, python closes the previous file. Closing the file with the close ( ) method is a good habit.

Syntax:

fileObject.close();

Example:

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

The following example outputs the results:

文件名: foo.txt

Read and write files:

The file object provides a series of methods that let our files access easier. See how to read and write files using read ( ) and write ( ) methods.

Write ( ) method

The write ( ) method writes any string to an open file. It's important to note that the python string can be binary, not just literal text.

The write ( ) method doesn't add a line break ( 'n ') at the end of the string:

Syntax:

fileObject.write(string);

Here, the arguments passed are the contents to be written to the open file.

Example:

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

The above method creates the foo. Txt file and writes the received content to the file and closes the file eventually. If you open this file, you'll see the following:

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

Read ( ) method

The read ( ) method reads a string from an open file. It's important to note that the python string can be binary, not just literal text.

Syntax:

fileObject.read([count]);

Here, the parameter passed is the count of bytes to be read from the open file. This method reads at the beginning of the file, and if no count is passed, it attempts to read more content as much as possible, 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()

The following example outputs the results:

读取的字符串是 : www.runoob

File location:

File location

A tell ( ) method tells you the current position within your file; In other words, the next happens after the file begins so many bytes.

Seek ( offset [, from ] ) method changes the location of the current file. Offset variable represents the number of bytes to move. A from variable specifies a reference location to begin moving bytes.

If from is set to 0, this means that the start of the file as a reference location for the move byte. If set to 1, use the current location as a reference location. If it's set to 2, the end of the file will be a reference location.

Example:

Use the file foo. Txt we created above.

#!/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()

The following example outputs the results:

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

Rename and delete files

Python 's os module provides a way to perform file processing operations such as renaming and deleting files.

To use this module, you must enter it before you can call the relevant various functions.

Rename ( ) method:

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

Syntax:

os.rename(current_file_name, new_file_name)

Example:

The following example will rename an existing file test1. Txt.

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

Remove ( ) method

You can delete files with the remove ( ) method, and you need to provide the file name to delete.

Syntax:

os.remove(file_name)

Example:

The following example deletes a file that already exists.

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

Directory in python:

All files are included in different directories, but python can easily handle all of them. Os modules have many ways to help you create, delete, and change directories.

Mkdir ( ) method

You can create new directories under the current directory using the mkdir ( ) method of the os module. You need to provide a parameter that contains the name of the directory to be created.

Syntax:

os.mkdir("newdir")

Example:

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

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

Chdir ( ) method

You can change the current directory with the chdir ( ) method. The ( ) method requires a parameter that you want to set the directory name to the current directory.

Syntax:

os.chdir("newdir")

Example:

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

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

Getcwd ( ) method:

A ( ) method displays the current working directory.

Syntax:

os.getcwd()

Example:

The following example gives the current directory:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
# 给出当前的目录
print os.getcwd()

Rmdir ( ) method

The xalan ( ) method deletes the directory, directory name, paramete &.

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

Syntax:

os.rmdir('dirname')

Example:

Here's an example of deleting the/tmp/test directory. The fully compliant name of the directory must be given, otherwise the directory is searched under the current directory.

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

File, directory related methods

Three important methods of approach can be used to make a wide and practical processing and manipulation of files and directories on windows and unix operating systems, as follows:

  • A file object method: file object provides a series of methods for manipulating files.
  • A os object method that provides a series of methods to handle files and directories.
  • Python file ( files ) method

    File objects are created using the open function, and the following table lists the functio & commonly used by the file object:

    Ordinal method and description
    1

    file. Close ( ).

    Close file. After closing, file cannot be read and write again.

    2

    file. Flush ( ).

    Flush the file internal buffer, directly write the data of the internal buffer to the file, not the passive wait output buffer write.

    3

    file. Fileno ( ).

    Returns an integer file descriptor ( file descriptor fd integer ) that can be used on some underlying operations such as the read method for os modules.

    4

    file. Isatty ( ).

    Return false if the file is connected to a terminal device.

    5

    file. Next ( ).

    Retur & the next line of the file.

    6

    file. Read ( [ size ] ).

    Reads the specified number of bytes from a file, and reads all of the specified bytes.

    7

    file. Readline ( [ size ] ).

    Read entire row, including"n"character.

    8

    [ sizehint ]

    All rows are read and returned. If sizeint> 0 is given, the sum of the sum of the sum of sizeint bytes is returned, the actual read value may be larger than sizhint.

    9

    [. Seek ( whence ] ).

    Set the current location of the file

    10

    file. Tell ( ).

    Returns the current location of the file.

    11

    file. Truncate ( [ size ] ).

    Intercept the file, the captured bytes are specified by size, and the default is the current file location.

    12

    file. Write ( str ).

    Writes a string to a file without a return value.

    13

    file. Writelines ( sequence ).

    To write a list of sequence strings to a file, if you need a line break, you want to add a line break to each line.

    Note list

  • YukiMirai

    Jol * * * @ 163. Com.

    After write content, the direct read file output is empty because the pointer is already at the end of the content.

    Two solutions: first, close the file, and then read it again, the second, you can set the pointer back to the file

    # -*- coding: UTF-8 -*-
    import os;
    document = open("testfile.txt","w+");
    print"文件名:", document.name;
    document.write("这是我创建的第一个测试文件!nwelcome!");
    print document.tell();
    #输出当前指针位置
    document.seek(os.SEEK_SET);
    #设置指针回到文件最初
    context = document.read();
    print context;
    document.close();
    yukimirai

    YukiMirai

    Jol * * * @ 163. Com.

    3 weeks ago ( 08-07 )




Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs