1.open(filePath,type)方法:打开文件

  filePath:文件路径

  type:操作文件的方式(r:读取,w:覆盖写入,a:追加写入)

2.strip()方法:去除读取到的每行内容后的换行符

stream = open('E:/projects/Python/test/fileopen.txt','r') #读取

print('打印一下原文件中的内容.....')
for line in stream:
print(line.strip()) #strip()方法可以去除结尾的换行符
stream.close() stream = open('E:/projects/Python/test/fileopen.txt','w') #写入,写入参数为w时,写入会覆盖原有内容
stream.write('Lucky:11个\n')
stream.close() print('打印一下使用w写入后的文件内容.....')
stream = open('E:/projects/Python/test/fileopen.txt','r') #读取
for line in stream:
print(line.strip()) #strip()方法可以去除结尾的换行符
stream.close() stream = open('E:/projects/Python/test/fileopen.txt','a') #写入,写入参数为a时,写入不会覆盖原有内容,而是追加写入
stream.write('Baby:11个\n')
stream.close() print('打印一下使用a写入后的文件内容.....')
stream = open('E:/projects/Python/test/fileopen.txt','r') #读取
for line in stream:
print(line.strip()) #strip()方法可以去除结尾的换行符
stream.close()

执行结果:

打印一下原文件中的内容.....
张三:5个
李四:10个
王五:20个
打印一下使用w写入后的文件内容.....
Lucky:11个
打印一下使用a写入后的文件内容.....
Lucky:11个
Baby:11个

05-28 23:39