ID:Computer-network

读写文件是最常见的IO操作。内置了读写文件的函数python文件读写,用法和的读写文件非常类似。在磁盘上读写文件的功能都是由提供的,现代不允许普通的程序直接操作磁盘,所以,读写文件就是请求打开一个文件对象(通常称为文件描述符),然后,通过提供的接口从这个文件对象中读取数据(读文件),或者把数据写入这个文件对象(写文件)。

1、Project分析

使用内置函数open来读写文件。查看open函数的帮助文档。执行命令:

python3

help(open)

执行的结果如图1所示。

图1 help open

图1中的Name是需要操作的文件名,mode是模式。这个模式共有7种,如表1所示。

python文件读写_python读dat文件_python写json文件

表1 Python Open Mode

这7种模式可以组合使用。下面将用创建一个文件,并写入、读取内容。

2、Project实施

编写operaFile.py,打开Putty连接到,执行命令:

cd code/crawler

vioperaFile.py

operaFile.py的代码如下:

1 #!/usr/bin/env python3

2 #-*- coding: utf-8 -*-

3 __author__ = ‘hst_king hst_king@hotmail.com’

4

5 import os

6

7 def operaFile(): #创建文件

8 print(‘创建一个名字为test.txt的文件,并在其中写入Hello Python’)

9 print(‘先得保证test.txt不存在’)

10 os.system(‘rm test.txt’)

11 os.system(‘ls -l test.txt’)

12 print(‘现在再来创建文件并写入内容n’)

13 fp = open(‘test.txt’, ‘w’)

14 fp.write(‘Hello Python’)

15 fp.close()

16 print(‘不要忘记用close关闭文件哦’)

17 print(‘再来看看test.txt是否存在python文件读写,和内容n’)

18 os.system(‘ls -l test.txt’)

19 os.system(‘cat test.txt’)

20 print(‘n’)

21

22 print(‘如何避免open文件失败的问题呢?’)

23 print(‘使用with as就可以了’)

24 with open(‘test.txt’, ‘r’) as fp:

25 st = fp.read()

26 print(‘test.txt的内容为:%s’ %st)

27

28 if __name__ == ‘__main__’:

29 operaFile()

执行命令:

python3operaFile.py

得到的结果如图2所示。

python读dat文件_python文件读写_python写json文件

图2 Python读写文件

对文件的操作跟类似,但功能远比要丰富。例如按行读取文件,多行读取文件等。的优势是快,而的优势是模块多、功能丰富。

限 时 特 惠: 本站每日持续更新海量各大内部创业教程,一年会员只需98元,全站资源免费下载 点击查看详情
站 长 微 信: muyang-0410