Python study notes -Python file I / O

Printed to the screen

The easiest method is to use the print statement output, you can pass zero or more comma-separated expression to it. This function converts the expression into you pass a string expression, and the result is written to standard output is 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 functions built from standard input line of text, the default standard input is a keyboard. as follows:

  • raw_input
  • input

raw_input function (Python 2.X)

raw_input ([prompt]) function reads a line from the standard input, and returns a string (removing the trailing newline):

#!/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])  functions substantially similar to, but a Python expression input may be received as input, and the calculation result is returned.

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

This will produce the following results corresponding to input:

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

Open and close the file

Now that you can 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 of the default file basic operation. You can use the  file  objects do most file operations.

open function

You must use Python's built-in open () function to open a file, create a file object associated method 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 value containing the name of the file you want to access.
  • access_mode: access_mode decided to open the file mode: Read, Write, and additions. See a complete list of all possible values ​​as follows. This parameter is not mandatory, the default file is read-only access mode (r).
  • buffering: If the value of buffering is set to 0 , there would be hosting . If the value of the buffering take 1, the line will register to access the file . If the value is an integer greater than 1 of buffering, indicating that this is the buffer size of the storage area . If you take a negative value, the buffer size storage area for the system default .

Open the complete list of the different modes of file: (b denotes a binary)

mode description
t Text mode (default).
x Write mode, create a new file, if the file already exists it will error.
b Binary mode.
+ Open a file is updated (read and write).
The Universal wrap mode (not recommended).
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 in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode. Generally used for non-text files such as pictures and so on.
r+ Open a file for reading and writing. The file pointer will be placed at the beginning of the file.
rb+ Opens a file for reading and writing binary format. The file pointer will be placed at the beginning of the file. Generally used for non-text files such as pictures and so on.
w Open a file for writing only. If the file already exists then open the file and start editing from the beginning, that is, the original content will be deleted. 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 then open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file. Generally used for non-text files such as pictures and so on.
w+ Open a file for reading and writing. If the file already exists then open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
wb+ Opens a file for reading and writing binary format. If the file already exists then open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file. Generally used for non-text files such as pictures and so on.
a Open a file for append. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written after the existing content. If the file does not exist, create a new file for writing.
from Open a file in binary format for additional. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written after 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 would append mode when the file is opened. If the file does not exist, create a new file for reading and writing.
ab + Open a file in binary format for additional. 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.

The figure below summarizes well these types of models:

mode r r+ w w+ a a+
read + +   +   +
write   + + + + +
create     + + + +
cover     + +    
Pointer at the start + + + +    
At the end of the pointer         + +

File object properties

After a file is opened, you have a file object, you can get various information about the file.

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

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

Following examples:

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

Examples of the above output:

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

close () method

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

When a file object reference is re-assigned to another file, Python will close the file before. Close the file with a close () method is a good habit.

grammar:

fileObject.close()

example:

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

Examples of the above output:

文件名:  foo.txt

Read and write files:

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

write () method

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

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

grammar:

fileObject.write(string)

在这里,被传递的参数是要写入到已打开文件的内容。

例子:

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

上述方法会创建foo.txt文件,并将收到的内容写入该文件,并最终关闭文件。如果你打开这个文件,将看到以下内容:

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

read()方法

read()方法从一个打开的文件中读取一个字符串。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。

语法:

fileObject.read([count])

在这里,被传递的参数是要从已打开文件中读取的字节计数。该方法从文件的开头开始读入,如果没有传入count,它会尝试尽可能多地读取更多的内容,很可能是直到文件的末尾。

例子:

这里我们用到以上创建的 foo.txt 文件。

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

以上实例输出结果:

读取的字符串是 :  www.runoob

文件位置:


文件定位

tell()方法告诉你文件内的当前位置, 换句话说,下一次的读写会发生在文件开头多少字节之后

seek(offset [,from])方法改变当前文件的位置Offset变量表示要移动的字节数。From变量指定开始移动字节的参考位置

如果from被设为0,这意味着将文件的开头作为移动字节的参考位置。如果设为1,则使用当前的位置作为参考位置。如果它被设为2,那么该文件的末尾将作为参考位置

例子:

就用我们上面创建的文件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()

以上实例输出结果:

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

重命名和删除文件

Python的os模块提供了帮你执行文件处理操作的方法,比如重命名和删除文件。

要使用这个模块,你必须先导入它,然后才可以调用相关的各种功能。

rename()方法:

rename()方法需要两个参数,当前的文件名和新文件名。

语法:

os.rename(current_file_name, new_file_name)

例子:

下例将重命名一个已经存在的文件test1.txt。

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

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

remove()方法

你可以用remove()方法删除文件,需要提供要删除的文件名作为参数。

语法:

os.remove(file_name)

例子:

下例将删除一个已经存在的文件test2.txt。

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

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

Python里的目录:

所有文件都包含在各个不同的目录下,不过Python也能轻松处理。os模块有许多方法能帮你创建,删除和更改目录。

mkdir()方法

可以使用os模块的mkdir()方法在当前目录下创建新的目录们。你需要提供一个包含了要创建的目录名称的参数。

语法:

os.mkdir("newdir")

例子:

下例将在当前目录下创建一个新目录test。

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

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

chdir()方法(CHange DIRectory)

可以用chdir()方法来改变当前的目录。chdir()方法需要的一个参数是你想设成当前目录的目录名称。

语法:

os.chdir("newdir")

例子:

下例将进入"/home/newdir"目录。

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

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

getcwd()方法:(GET Current Working Directory)

getcwd()方法显示当前的工作目录

语法:

os.getcwd()

例子:

下例给出当前目录:

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

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

rmdir()方法(RoMove DIRectory)

rmdir()方法删除目录,目录名称以参数传递。

在删除这个目录之前,它的所有内容应该先被清除。

语法:

os.rmdir('dirname')

例子:

以下是删除" /tmp/test"目录的例子。目录的完全合规的名称必须被给出,否则会在当前目录下搜索该目录。

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

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

 

发布了19 篇原创文章 · 获赞 0 · 访问量 809

Guess you like

Origin blog.csdn.net/weixin_44151772/article/details/104035316