• 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()
  • 相关阅读:
    创建对象的模式
    linux下安装node v12.16.3
    es6知识点总结
    在阿里云上部署的node服务器不能通过公网IP访问
    angular 1 input中选中状态绑定
    让一个元素水平垂直居中
    语录收集
    跨域
    事件循环
    git的常用命令
  • 原文地址:https://www.cnblogs.com/laotieshan/p/13207528.html
Copyright © 2020-2023  润新知