python笔记学习 第1篇 【文件读写】

读文件

  1. 打开文件
  2. 读文件
  3. 关闭文件

file1 = open(’/Users/motanyuan/Desktop/abc.txt’,‘r’,encoding=‘utf-8’) #打开文件
filecontent = file1.read() # 读文件
print(filecontent) # 打印文件内容
file1.close() # 关闭文件

写文件

覆盖原来内容的写

  1. 打开文件
  2. 写文件
  3. 关闭文件

file1 = open(’/Users/motanyuan/Desktop/abc.txt’, w ,encoding = ‘utf-8’)
file1.write(‘张无忌\n’)
file1.write(‘宋青书\n’)
file1.close()

不覆盖原来内容的写

file1 = open(’/Users/motanyuan/Desktop/abc.txt’, ‘a’,encoding=‘utf-8’)
#以追加的方式打开文件abc.txt
file1.write(‘张无忌\n’)
#把字符串’张无忌’写入文件file1
file1.write(‘宋青书\n’)
#把字符串’宋青书’写入文件file1
file1.close()

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Jacky_programming/article/details/87881550