zoukankan      html  css  js  c++  java
  • Python file 文件读写

    需要自己创建好 test_file 文件及内容。

     1 #!/usr/bin/env python3
     2 # -*- coding: utf-8 -*-
     3 
     4 '''
     5 #写是重新生成一个新的文件,如果用同名文件会将原来的文件内容清空,请注意
     6 file = open('test_file', mode='w', encoding='utf-8')
     7 file.write("ceshi neirong")
     8 file.close()
     9 
    10 #追加内容 a 是append的简写
    11 file = open('test_file', mode='a', encoding='utf-8')
    12 file.write("
    ceshi neirong 2222222")
    13 file.close()
    14 
    15 file = open('test_file', mode='r+', encoding='utf-8')           #读写,先读取再写入
    16 file = open('test_file', mode='w+', encoding='utf-8')           #读写,先写入再读取
    17 file = open('test_file', mode='a+', encoding='utf-8')           #追加读
    18 
    19 file = open('test_file', mode='rb', encoding='utf-8')           #二进制文件读
    20 file = open('test_file', mode='wb', encoding='utf-8')           #二进制文件写
    21 
    22 '''
    23 
    24 
    25 #只读文件内容
    26 file = open('test_file', mode='r', encoding='utf-8')
    27 #print(file.read())
    28 
    29 
    30 print(file.read(1))                         #读取第1个字节,留空则表示全部内容
    31 print(file.readlines(1))                    #读取第1行内容,留空则表示一行
    32 print("".center(50, "-"))
    33 
    34 print(file.seek(0))                 #跳到字节的哪一个位置
    35 print(file.tell())                  #显示字节当前位置
    36 
    37 print(file.encoding)                #查询文件编码格式
    38 
    39 file.flush()     #实时将内容刷新到硬盘上!!!
    40 
    41 
    42 
    43 #查询前10行
    44 count = 0
    45 for line in file:
    46     if count == 10 :
    47         print("".center(40, '*'))
    48         count +=1
    49         continue
    50     print(line.strip())
    51     count +=1
    人生天地间,忽如远行客。
  • 相关阅读:
    取得system32文件夹下面文件的写入权限
    几个SQL语句(备忘)
    Excel多表合并的宏
    删除系统旧网卡
    Eclipse 迁移到Android studio
    是否使用安全模式启动word
    微信公众平台开发
    delphi安装 Tclientsocket, Tserversocket控件
    win10 Internet Explorer 11 停止工作处理
    java编译出错信息汇总(更新)
  • 原文地址:https://www.cnblogs.com/voua/p/11656128.html
Copyright © 2011-2022 走看看