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

综述

  • 在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\n')
In [30]: f.write('message #2\n')
In [31]: f.write('message #3\n')
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语句会自动关闭文件。

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值