zoukankan      html  css  js  c++  java
  • 2020-6-29-Python3-文件的操作

     1 # -*- coding:utf-8 -*-
     2 __author__ = 'admin'
     3 #readlines(),第一次读时将文件全部读出,以换行符为分隔生成列表,第二次读时为空列表。
     4 #为了对读出的内容进行多次处理时,将readlines()赋值给变量
     5 #写文件
     6 f = open('test.log', 'w')
     7 f.write('This is the first line!
    ')
     8 f.write('This is the second line!')
     9 f.close()
    10 
    11 #readlines()读文件
    12 f = open('test.log', 'r')
    13 f_list = f.readlines()
    14 f.close()
    15 print(f_list[0])
    16 print(f_list[1])
    17 
    18 #read()读文件
    19 f = open('test.log', 'r')
    20 f_read = f.read()
    21 f.close()
    22 print(f_read)
    23 
    24 #readline()读文件
    25 f = open('test.log', 'r')
    26 f_readline = f.readline()
    27 f.close()
    28 print(f_readline)
    29 
    30 #另1:readlines()用在for循环中是可以的
    31 f = open('test.log', 'r')
    32 for line in f.readlines():
    33     print(line)
    34 f.close()
    35 
    36 #但当文件特别大时,不建议使用read()或readlines(),建议使用内置迭代方式
    37 f = open('test.log', 'r')
    38 for line in f:
    39     print(line)
    40 f.close()
    41 
    42 #另2:strip()不改变字符串原值,append()改变列表原值
    43 f = open('test.log', 'r')
    44 lines = []
    45 for line in f.readlines():
    46     print(line.strip('
    '))
    47     lines.append(line.strip())
    48     print(line)
    49     print(lines)
    50 f.close()
  • 相关阅读:
    MFC中DoDataExchange()的作用
    图片下面出现空白像素的问题解决
    nginx 的 autoindex on首页不显示的问题 按照下面几行要写上不然不行
    配置 PHP 的 Session 存储到 Redis
    redis4安装
    jumpserver安装
    mysql命令参数详解
    定制LNMP的RPM包
    NTP原理
    内网环境NTP服务及时间同步(CentOS6.x)配置和部署
  • 原文地址:https://www.cnblogs.com/laotieshan/p/13207528.html
Copyright © 2011-2022 走看看