Python笨办法学Python玩耍Python

Python: 文件操作

2016-07-12  本文已影响268人  心智万花筒

文件操作

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

打开文件

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

关闭文件

f.close()

模式

写入文件

注意,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()

读文件

总共有三个模式:

读取所有内容
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
上一篇 下一篇

猜你喜欢

热点阅读