牛骨文教育服务平台(让学习变的简单)
博文笔记

【Python那些事儿】Python中的读写文件

创建时间:2016-10-30 投稿人: 浏览次数:6285

综述

  • 在Python中读写文件,你不需要导入任何库;
  • 第一步就是获取文件对象;
  • 主要利用“open()”函数。

文件类型

  • 文本文件
  • 二进制文件

Open()函数

  • 打开文件进行读写操作,需要使用Python的内置函数:open()。它返回一个文件对象,最常用的参数有两个。
  • 你也可以使用file()函数,但是推荐使用open()。
  • 语法:
file_object = open(filename, mode) where file_object is the variable to put the
file object.

Example:

In [28]: f = open("mylog.txt", "w")
In [29]: f.write("message #1
")
In [30]: f.write("message #2
")
In [31]: f.write("message #3
")
In [32]: f.close()
In [33]: f = file("mylog.txt", "r")
In [34]: for line in f:
   ....:     print line,
   ....:
message #1
message #2
message #3
In [35]: f.close()
  • 第二个参数描述的是文件的使用模式。
    • mode参数是可选项,默认省略是’r’;
    • modes:’r’代表只读;’w’代表只写(具有相同名称的文件将被删除);’a’代表追加到文件(任何写的数据将被自动追加到文件的后面);’r+’代表打开文件进行读写操作。
infile = open("myfile.txt", "r")    # open for reading
outfile = open("myfile.txt", "w")   # open for (over-) writing
log = open("myfile.txt", "a")       # open for appending to existing content

创建一个文件

首先我们创建一个新的文件。你可以随意给它命名,在这个例子里我们将其命名为’newfile.txt’。

file = open("newfile.txt", "w")

file.write("hello world in the new file
")

file.write("and another line
")

file.close()

我们可以使用命令查看文件的内容:

$ cat newfile.txt 
hello world in the new file
and another line

如何读取一个文件

要读取一个文件,我们可以使用不同的方法:

  • file.read([count]):读出文件,如果有count,则读出count个字节;
  • file.readline():读出一行信息;
  • file.readlines():读出所有行,返回包含所有行的列表。

遍历一个文件对象

file = open("newfile.txt", "r")

for line in file:
    print line

输出:

hello world in the new file
and another line

file.write()

write方法只有一个参数,即需要写入的字符串。

file = open("newfile.txt", "w")

file.write("This is a test
")

file.write("And here is another line
")

file.close()

file.close()

当操作完文件后,需要使用file.close()方法关闭文件,释放出打开文件而占用的系统资源。调用该方法后,将不能再继续对文件进行操作。

‘With’语句

  • 文件操作的另外一种方法是with语句。使用这个语句是一个很好的方法,你将获得更好的语法和异常异常处理。
  • with语句会自动关闭打开的文件。

用with语句打开一个文件:

with open(filename) as file:

再看看其他一些操作:

with open("newtext.txt") as file:   # Use file to refer to the file object
    data = file.read()
    do something with data

你当然也可以遍历整个文件对象:

with open("newfile.txt") as f:
    for line in f:
        print line
  • 为了打开多个文件,可以使用with嵌套语句,或者是用一个with语句:
def test():
    #
    # use multiple nested with: statements.
    with open("small_file.txt", "r") as infile:
        with open("tmp_outfile.txt", "w") as outfile:
            for line in infile:
                outfile.write("line: %s" % line.upper())
    print infile
    print outfile
    #
    # use a single with: statement.
    with open("small_file.txt", "r") as infile, 
            open("tmp_outfile.txt", "w") as outfile:
        for line in infile:
            outfile.write("line: %s" % line.upper())
    print infile
    print outfile

test()

注意:不需要再使用file.close()方法关闭打开的文件。with语句会自动关闭文件。

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。