前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python: 文件操作

Python: 文件操作

作者头像
用户2183996
发布2018-06-21 17:47:28
6450
发布2018-06-21 17:47:28
举报
文章被收录于专栏:技术沉淀

文件操作

文件操作,无外乎读写,但首先你要打开文件。

打开文件

f = open(filename, mode) filename是文件名,可以带目录;mode是读写模式(可以是读,写,追加等);f是file handler。

关闭文件

f.close()

模式

  • "r": Open a file for read only
  • "w": Open a file for writing. If file already exists its data will be cleared before opening. Otherwise new file will be created
  • "a": Opens a file in append mode i.e to write a data to the end of the file
  • "wb": Open a file to write in binary mode
  • "rb": Open a file to read in binary mode

写入文件

注意,write不会自动加入\n,这一点不像print

代码语言:javascript
复制
f = open('myfile.txt', 'w')    # open file for writing
f.write('this is first line\n')   # write a line to the file
f.write('this is second line\n')  # write one more line
f.close()

读文件

总共有三个模式:

  • read([number]): Return specified number of characters from the file. if omitted it will read the entire contents of the file.
  • readline(): Return the next line of the file.
  • readlines(): Read all the lines as a list of strings in the file
读取所有内容
代码语言:javascript
复制
f = open('myfile.txt', 'r')
f.read()
代码语言:javascript
复制
'this is first line\nthis is second line\n'
代码语言:javascript
复制
f.close()
读取所有行
代码语言:javascript
复制
f = open('myfile.txt','r')
f.readlines()
代码语言:javascript
复制
['this is first line\n', 'this is second line\n']
代码语言:javascript
复制
f.close()
读取一行
代码语言:javascript
复制
f = open('myfile.txt','r')
f.readline()
代码语言:javascript
复制
'this is first line\n'
代码语言:javascript
复制
f.close()

Append

代码语言:javascript
复制
f = open('myfile.txt','a')
f.write('this is third line\n')
代码语言:javascript
复制
f.close()

遍历文件数据

代码语言:javascript
复制
f = open('myfile.txt','r')
for line in f:
    print line,
代码语言:javascript
复制
this is first line
this is second line
this is third line
代码语言:javascript
复制
f.close()

with open

代码语言:javascript
复制
with open('myfile.txt','r') as f:
    for line in f:
        print line,
代码语言:javascript
复制
this first line
this second line
this is third line
代码语言:javascript
复制
with open('myfile.txt','r') as f:
    for line in f.readlines():
        print line,    
代码语言:javascript
复制
this is first line
this is second line
this is third line
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016.07.12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文件操作
    • 打开文件
      • 关闭文件
        • 模式
          • 写入文件
            • 读文件
              • Append
                • 遍历文件数据
                  • with open
                  领券
                  问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档