本文共 2803 字,大约阅读时间需要 9 分钟。
对数据文件的操作是Python的内置模块,只要使用open函数,根据文件的打开模式,获取到文件的句柄,就可以对文件进行读、写、追加操作。语法形式如下:
方式一:fp = open(“文件名”,“文件打开模式”)
方式二:with open("文件名") as fp:
如果打开了文件之后就不再处理该文件了,那么使用with语句可以使程序编写得更为简洁,离开with之后,系统自动会关闭文件相关的内容,就不需要主动使用fp.close()了。
春晓.txt: 《春晓》春眠不觉晓,处处闻啼鸟。夜来风雨声,花落知多少。 drawOfSpring.txt: Dawn of Spring I wake up at the dawn of Spring, And hear the birds ev'rywhere sing. As sounded the wind and rain o'ernight, I wonder how many blooms alight.
fp = open("春晓.txt","r+")spring = fp.readlines()#fp.close()i=1print("-----------诗词翻译:方式一-----------")for statement in spring: print("line {}: {}".format(i,statement),end="") i +=1print()files = []with open('dawnOfSpring.txt') as fpoint: files = fpoint.readlines()i=1print("-----------诗词翻译:方式二-----------")for statement in files: fp.write(statement) print("line {}: {}".format(i,statement),end="") i +=1fp.close()3、执行后,显示的结果如下:
-----------诗词翻译:方式一-----------line 1: 《春晓》line 2: line 3: 春眠不觉晓,处处闻啼鸟。line 4: 夜来风雨声,花落知多少。 line 5: -----------诗词翻译:方式二-----------line 1: line 2: Dawn of Springline 3: I wake up at the dawn of Spring, line 4: And hear the birds ev'rywhere sing. line 5: As sounded the wind and rain o'ernight, line 6: I wonder how many blooms alight.Process finished with exit code 04、用文本编辑器打开“春晓.txt”文件,结果是这样子的: 《春晓》 春眠不觉晓,处处闻啼鸟。 夜来风雨声,花落知多少。 Dawn of Spring I wake up at the dawn of Spring, And hear the birds ev'rywhere sing. As sounded the wind and rain o'ernight, I wonder how many blooms alight.
转载地址:http://aolfb.baihongyu.com/