python 文件读写

open()是python的内置函数,它会返回一个文件对象,这个文件对象拥有read、readline、write、close等方法。

语法:open('file','mode')
参数说明:file:需要打开的文件路径 mode(可选):打开文件的模式,如只读("r")、追加("a")、写入("w")等
常见使用:
f = open(file) # 打开文件
f.close() # 关闭文件

读写文件3个步骤

  • 调用open()函数,返回一个File对象
  • 调用File对象的read()或write()方法
  • 调用File对象的close()方法,关闭该文件

读取文件:

  • helloFile = open('C:\\Users\\Administrator\\Desktop\\url.txt')  
  • helloContent = helloFile.read()
  • helloFile.close()

写入文件

  • helloFile = open('C:\\Users\\Administrator\\Desktop\\url.txt', 'w')  
  • helloFile.write('Hello world!\n')
  • helloFile.close()
posted @ 2018-09-28 14:58  keep2021  阅读(109)  评论(0编辑  收藏  举报