Python文件读写

文件操作,无外乎读写,但首先你要打开文件,本文简要介绍,原文见Python文件读写

打开文件

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

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
读取所有内容
f = open('myfile.txt', 'r')
f.read()
'this is first line\nthis is second line\n'
f.close()
读取所有行
f = open('myfile.txt','r')
f.readlines()
['this is first line\n', 'this is second line\n']
f.close()
读取一行
f = open('myfile.txt','r')
f.readline()
'this is first line\n'
f.close()

Append

f = open('myfile.txt','a')
f.write('this is third line\n')
f.close()

遍历文件数据

f = open('myfile.txt','r')
for line in f:
    print line,
this is first line
this is second line
this is third line
f.close()

with open

with open('myfile.txt','r') as f:
    for line in f:
        print line,
this first line
this second line
this is third line
with open('myfile.txt','r') as f:
    for line in f.readlines():
        print line,    
this is first line
this is second line
this is third line
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值