码迷,mamicode.com
首页 > 编程语言 > 详细

[Python Study Notes]文件操作

时间:2018-01-09 16:53:04      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:att   删除   with   nbsp   note   iso   class   文件   int   

                     

 文件操作    

                                                                   

 

对文件操作流程

  1. 打开文件,可添加filepath打开某绝对路径下的文件,得到文件句柄并赋值给一个变量
  2. 通过句柄对文件进行操作
  3. 关闭文件
 1 # The_author = ‘liu66‘
 2 # -*- coding = utf-8 -*-
 3 
 4 filepath=D:\学习资料\ehmatthes-pcc-6bfeca0\chapter_10\pi_digits.txt
 5 
 6 read_sting = ‘‘
 7 
 8 with open(filepath) as file_object:
 9     #contents=file_object.read()
10     # print(contents)
11     # ‘‘‘删除末尾空行‘‘‘
12     # print(contents.rstrip())
13 
14     ‘‘‘逐行打印‘‘‘
15     for line in file_object:
16     #     ‘‘‘两行空白,一行来自文件,一行来自print‘‘‘
17     #     print(line)
18     #     ‘‘‘去掉文件换行‘‘‘
19         # print(line.rstrip())
20 
21         ‘‘‘删除所有空格‘‘‘
22         read_sting+=line.strip()
23 file_object.close()
24 print(read_sting)
25 print(len(read_sting))

 

打开文件的模式有:

  • r,只读模式(默认)。
  • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
  • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

 

"+" 表示可以同时读写某个文件

  • r+,可读写文件。【可读;可写;可追加】
  • w+,写读
  • a+,同a

 

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)

  • rU
  • r+U

 

"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

  • rb
  • wb
  • ab

[Python Study Notes]文件操作

标签:att   删除   with   nbsp   note   iso   class   文件   int   

原文地址:https://www.cnblogs.com/liu66blog/p/8251565.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!