• [Python Study Notes]文件操作


                         

     文件操作    

                                                                       

     

    对文件操作流程

    1. 打开文件,可添加filepath打开某绝对路径下的文件,得到文件句柄并赋值给一个变量
    2. 通过句柄对文件进行操作
    3. 关闭文件
     1 # The_author = 'liu66'
     2 # -*- coding = utf-8 -*-
     3 
     4 filepath='D:学习资料ehmatthes-pcc-6bfeca0chapter_10pi_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 或 r+ 模式同使用)

    • rU
    • r+U

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

    • rb
    • wb
    • ab
    最有用的语言,除了English,其次可能是Python
  • 相关阅读:
    radio checkbox select
    easyui_tree
    MySQL编码问题
    Django shell调试
    encode,decode
    结束进程
    Django models 字段
    re
    (转)为Ubuntu安装翻译词典(星际译王)
    python3进阶之正则表达式之基本概念
  • 原文地址:https://www.cnblogs.com/liu66blog/p/8251565.html
Copyright © 2020-2023  润新知