13. python文件和流

  1. 读文件和写文件
  2. 管道输出
  3. 读行和写行
  4. 使用FileInput对象读取文件

读文件和写文件

'''
读文件和写文件

r: 读
w: 写
r+:文件可读写,如果文件不存在,会抛出异常。如果文件存在,会从当前位置开始
     写入新内容,通过seek函数可以改变当前的位置,也就是改变文件的指针。
w+:文件可读写,如果文件不存在,会创建一个新文件,如果文件存在,会清空整个
    文件,并写入新内容。
a+:文件可读写,如果文件不存在,会创建一个新文件,如果文件存在,会将要写入的
    内容添加到原文件的最后。也就是说,使用a+打开已经存在的文件,文件指针已经在文件的结尾了
'''

'''
write(string):向文件写入内容,该函数会返回写入文件的字节数。
read([n]):读取文件的内容,n是一个整数,表示从文件指针指定的位置开始读取的n个字节。
如果不指定n,该函数会读取从当前位置往后的所有的字节。该函数会返回读取的数据。

seek(n):重新设置文件指针,也就是改变文件的当前位置。如果使用write函数写入内容后
需要使用seek(0)重置文件指针

close():关闭文件,对文件进行读写操作后,关闭文件是一个好习惯。
'''

# 以写模式打开文件
# 目录不存在,会报错;文件不存在,会创建一个文件
f = open('./files/test1.txt', 'w')
# 向文件中写入内容, 返回的是写入的字节数
print(f.write('Life is short, '))     # 15
print(f.write('you need python.')) # 16
f.close()

# 读文件
f = open('./files/test1.txt', 'r')
print(f.read(15))
print(f.read(16))
f.close()

# r 文件不存在会抛出异常……废话吗
try:
    f = open('./files/test2.txt', 'r')
except Exception as e:
    print(e)
    
# a+ 模式
f = open('./files/test2.txt', 'a+')
f.write('hellokitty')
f.close()

# f = open('./files/text2.txt', 'a+')  # 用a+模式打开文件,指针已经在最后了,所以第一个read没有结果
f = open('./files/test2.txt', 'r+')  # r 和 r+ 模式打开,指针在最开始,两次都是是可以读取的
print('1 >>> ', f.read())
f.seek(0)
print('2 >>> ', f.read())
f.close()

# w+ 搭配 seek 使用
try:
    f = open('./files/test2.txt', 'w+')
#     f = open('./files/test2.txt', 'a+')
    print(f.read())
    f.write('Are you OK?')
    f.seek(0)
    print(f.read())
finally:
    f.close()

管道输出

模拟了一个grep的操作:

'''
从标准输入读取所有的数据,并按行将数据保存到列表中,然后
过滤出所有包含“readme”的行,并输出这些行
'''

import sys, os, re

# 从标准输入读取全部数据
text = sys.stdin.read()

files = text.split(os.linesep)
for file in files:
    result = re.match('.*readme.*', file)
    if result != None: print(file)

读行与写行

import os
f = open('./files/urls.txt', 'r+')
url = ''

while True:
    url = f.readline()
    url = url.rstrip()   # trim
    if url == '': break
    else: print(url)
print('============')
f.seek(0)

print(f.readlines())

f.write('www.baidu.com' + os.linesep)
f.close()

# 批量写入行
f = open('./files/urls.txt', 'a+')
urlList = ['www.zhihu.com' + os.linesep, 'www.weibo.com' + os.linesep]
#urlList = ['www.zhihu.com', 'www.weibo.com']
f.writelines(urlList)
f.close()

使用FileInput对象读取文件

import fileinput

fileobj = fileinput.input('./files/urls.txt')
print(type(fileobj))  # 

# print(fileobj.readline().rstrip())
# print(fileobj.readline().rstrip())
# print(fileobj.readline().rstrip())

for line in fileobj:
    line = line.rstrip()
    if line != '':
        print(fileobj.lineno(), ' : ', line)
    else:
        print(fileobj.filename())

练习1

'''
编写一个Python程序,从控制台输入一个奇数,
然后生成奇数行的星号(*)菱形,并将该菱形保存到当前目录下
的stars.txt文件中。
'''
def fun(num, sep = '*'):
    '''
输入一个奇数,打印菱形图案。
默认以'*'填充
    '''
    if num % 2 == 0: raise Exception('必须输入一个奇数')
#     maxLine = int((num + 1)/2 - 1)  # 宽度最大行的行号
#     print('maxLIne: ', maxLine) 
    for line in range(num):
        no = 0
        if line < (num + 1)/2: 
            no = line
        else: 
            no = num - line - 1
        yield '{str:^{cnt}}'.format(str = (2 * no + 1) * sep, cnt = num)

import os
f = open('./starts.txt', 'w+')
for str in fun(9):
    f.write(str + '\n')
f.close()

练习2

'''
编写一个Python程序,从当前目录的文本文件words.txt中读取所有
的内容(全都是英文单词),并统计其中每一个英文单词出现的次数。
单词之间用逗号(,)、分号(;)或空格分隔,也可能是这3个分隔符一起
分隔单词。将统计结果保存到字典中,并输出统计结果。

假设words.txt文件的内容如下:
test star test star star;bus  test bill ,   new yeah bill,book bike God start python what
'''
import re
f = open('words.txt','r')
words = f.read()
wordList = re.split('[ ,;]+',words)
print(wordList)
countDict = {}
for word in wordList:
    if countDict.get(word) == None:
        countDict[word] = 1
    else:
        countDict[word] = int(countDict[word]) + 1
for (key,value) in countDict.items():
    print(key,'=',value)
f.close()

你可能感兴趣的:(13. python文件和流)