Python 文件操作

参考来源:Magnus Lie Hetland 《Python基础教程》

1. open 

f = open('somefile.txt') # 文件名是唯一必不可少的参数,返还一个文件对象

2. 文件模式

类似于c++,open的参数mode(默认是 r 模式,即只读)

'r'

'w'

'x'  独占写入模式(如果文件已经存在,引发FileExistsError)

'a'  附加

'b'  二进制模式

't'  文本模式

'+'  读写模式

3. write, read

f = open('somefile.txt', 'w')
f.write('Hello, ')
f.write('World!')
f.close()

f = open('somefile.txt', 'r')
f.read(4)#读取4个字符
f.read()#读取剩下的所有内容

4. sys.stdin中包含多少个单词

#somescript.py
import sys
text = sys.stdin.read() #读取stdin中的所有内容
words = text.split() #将stdin中的所有内容分割成words
wordcount = len(words)
print('Wordcount:', wordcount)

5. 读取和写入行:readline, readlines, writelines

#readline
f = open(r'C:	extsomefile.txt')
for i in range(3):
    print(str(i) + ': ' + f.readline(), end = ' ')
#结果:
#0: Welcome to this file
#1: There is nothing here except
#2: This stupid haiku
f.close()

#readlines():
import pprint # pprint 之前没有接触过
pprint.pprint(open(r'C:	extsomefile.txt').readlines())
#结果:
#['Welcome to this file
',
#'There is nothing here except
',
#'This stupid haiku']

#writelines():
f = open(r'C:	extsomefile.txt')
lines = f.readlines()
f.close()
line[1] = "isn't a
"
f = open(r'C:	extsomefile.txt', 'w' )
f.writelines(lines)
f.close()

6. 迭代文件内容

with open(filename) as f : # 上下文管理器,结束后自动关闭文件
    while True:
        line = f.readline()
        if not line: break
        process(line) # process函数是自己写的,示例中作者写的process功能是输出line到 stdout
#fileinput: 只读取需要的部分,适用于很大的文件(无法一次读出所有内容)
import fileinput
for line in fileinput.input(filename):
    process(line)

7. 文件迭代器

文件对象作为一个迭代器使用,对文件内容进行逐行迭代

with open(filename) as f:
    for line in f:
        proccess(line)
for line in open(filename):
    process(line)
import sys #迭代标准输入内容
for line in sys.stdin:
    process(line)
原文地址:https://www.cnblogs.com/luyi07/p/14337509.html