700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Python小练习1:.txt文件常用读写操作

Python小练习1:.txt文件常用读写操作

时间:2020-07-10 22:43:40

相关推荐

Python小练习1:.txt文件常用读写操作

.txt文件常用读写操作

本文通过一个实例来介绍读写txt文件的各种常用操作,问题修改自coursera上南京大学的课程:用Python玩转数据。

直接进入正题,考虑下面为练习读写txt文件的各种操作而设计的一个具体问题

问题如下:

(1) 在任意位置创建一个.py文件,如'D:/编程练习/python练习/Week2_02.py'

(2) 在D盘下创建一个文件Blowing in the wind.txt,即‘D:\Blowing in the wind.txt’

其内容是:

How many roads must a man walk down

Before they call him a man

How many seas must a white dove sail

Before she sleeps in the sand

How many times must the cannon balls fly

Before they're forever banned

The answer my friend is blowing in the wind

The answer is blowing in the wind

(3) 在文件头部插入歌名“Blowin’ in the wind”

(4) 在歌名后插入歌手名“Bob Dylan”

(5) 在文件末尾加上字符串“1962 by Warner Bros. Inc.”

(6) 在屏幕上打印文件内容,最好加上自己的设计

(7) 以上每一个要求均作为一个独立的步骤进行,即每次都重新打开并操作文件

--------------------------------------------------------------------------------------------------------------------

程序代码如下:

import os#Python的os模块提供了执行文件和目录处理操作的函数,例如重命名和删除文件。os.chdir('D:\\') #更改目录 #-------------------------------------------------------------------------#创建一个文件,将歌词写入f1=open(r'Blowing in the wind.txt','w')f1.write('How many roads must a man walk down \n')f1.write('Before they call him a man \n')f1.write('How many seas must a white dove sail \n')f1.write('Before she sleeps in the sand \n')f1.write('How many times must the cannon balls fly \n')f1.write('Before they\'re forever banned \n')f1.write('The answer my friend is blowing in the wind \n')f1.write('The answer is blowing in the wind\n')f1.close()#文件使用后记得关闭#--------------------------------------------------------------------------#在文件头部插入歌曲名f2=open(r'Blowing in the wind.txt','r+')#mode参数不能用'w+',这会清空原内容lyrics =f2.readlines()lyrics.insert(0,'Blowin\'in the wind\n')#在第一行添加歌曲名f2.seek(0,0)#将文件指针移动到文件开头处f2.writelines(lyrics)f2.close()#这是一种错误的写法,将歌词的第一行抹去了一部分#f2=open(r'Blowing in the wind.txt','r+')#f2.seek(0,0)#将文件指针移动到文件开头处#f2.write('Blowin’ in the wind\n')#f2.close()#--------------------------------------------------------------------------#在歌名后插入歌手名(实现同上一步)f3=open(r'Blowing in the wind.txt','r+')#mode参数不能用'w+',这会清空原内容lyrics =f3.readlines()lyrics.insert(1,'——Bob Dylan\n')#在第一行添加歌手名f3.seek(0,0)#将文件指针移动到文件开头处f3.writelines(lyrics)f3.close()#--------------------------------------------------------------------------#在文件末尾加上字符串“1962 by Warner Bros. Inc.” f4=open(r'Blowing in the wind.txt','a')#mode参数选择'a',代表追加模式.f4.write('1962 by Warner Bros. Inc.')#追加模式下,可以直接向文件末尾write内容f4.close()#--------------------------------------------------------------------------#在屏幕上打印文件内容(最好加一些自己的格式设计)f5=open(r'Blowing in the wind.txt','r')article =f5.readlines()#读取文件内容#按照自己的方式显示for i in range(0,len(article)):if 1<i<len(article)-1:print('\t'+article[i])else:print('\t\t'+article[i])f5.close()

运行后.txt文件中的内容为:

屏幕上的输出为:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。