Python教程:文件和读写的详细教程

打印 上一主题 下一主题

主题 993|帖子 993|积分 2979

文件操作的模式

文件操作的模式如下表:

1. open 打开文件

使用 open 打开文件后一定要记得调用文件对象的 close() 方法。比如可以用 try/finally 语句来确保最后能关闭文件。
  1. file_object = open(r'D:\test.txt') # 打开文件
  2. try:
  3.      all_the_text = file_object.read( ) # 读文件的全部内容
  4. finally:
  5.      file_object.close( ) # 关闭文件
  6. print(all_the_text)
复制代码
注:不能把 open 语句放在 try 块里,因为当打开文件出现异常时,文件对象 file_object 无法执行 close() 方法。
2. 读文件

读文本文件方式打开文件
  1. file_object = open(r'D:\test.txt', 'r') # 打开文件
  2. #第二个参数默认为 r
  3. file_object = open(r'D:\test.txt') # 打开文件
复制代码
读二进制文件方式打开文件
  1. file_object= open(r'D:\test.txt', 'rb') # 打开文件
复制代码
读取所有内容
  1. file_object = open(r'D:\test.txt') # 打开文件
  2. try:
  3.      all_the_text = file_object.read( )# 读文件的全部内容
  4. finally:
  5.      file_object.close( ) # 关闭文件
  6. print(all_the_text)
复制代码
读固定字节
  1. file_object = open(r'D:\test.txt', 'rb') # 打开文件
  2. try:
  3.     while True:
  4.          chunk = file_object.read(100) # 读文件的100字节
  5.          if not chunk:
  6.             break
  7.          #do_something_with(chunk)
  8. finally:
  9.      file_object.close( ) # 关闭文件
复制代码
读每行 readlines
  1. file_object = open(r'D:\test.txt', 'r')  # 打开文件
  2. list_of_all_the_lines = file_object.readlines( ) #读取全部行
  3. print(list_of_all_the_lines)
  4. file_object.close( ) # 关闭文件
复制代码
如果文件是文本文件,还可以直接遍历文件对象获取每行:
  1. file_object = open(r'D:\test.txt', 'r') # 打开文件
  2. for line in file_object:
  3.     print(line)
  4. file_object.close( ) # 关闭文件
复制代码
3. 写文件

写文本文件方式打开文件
  1. file_object= open('data', 'w')
复制代码
写二进制文件方式打开文件
  1. file_object= open('data', 'wb')
复制代码
追加写文件方式打开文件
  1. file_object= open('data', 'w+')
复制代码
写数据
  1. '''
  2. 学习中遇到问题没人解答?小编创建了一个Python学习交流群:711312441
  3. 寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
  4. '''
  5. all_the_text="aaa\nbbb\nccc\n"
  6. file_object = open(r'D:\thefile.txt', 'w') # 打开文件
  7. file_object.write(all_the_text) #写入数据
  8. file_object.close( ) # 关闭文件
复制代码
写入多行
  1. all_the_text="aaa\nbbb\nccc\n"
  2. file_object = open(r'D:\thefile.txt', 'w')# 打开文件
  3. file_object.writelines(all_the_text) #写入数据
  4. file_object.close( ) # 关闭文件
复制代码
追加
  1. file = r'D:\thefile.txt'
  2. with open(file, 'a+') as f: # 打开文件
  3.      f.write('aaaaaaaaaa\n')  
复制代码
判断文件是否存在:
  1. import os.path
  2. if os.path.isfile("D:\\test.txt"): # 判断文件是否存在
  3.     print(":\\test.txt exists")
  4. import os
  5. os.getcwd()  # 获得当前目录
  6. os.chdir("D:\\test.txt") # 改变当前目录
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

南飓风

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表