zoukankan      html  css  js  c++  java
  • 文件和异常(一)

    通过处理文件,可以让程序快速的分析大量的数据;

    1,从文件中读取数据

    #!/usr/bin/env python

    #filename = read_pi.py

    with open('pi.txt') as file_object:

        contents = file_object.read()

        print(contents)

    这段代码的核心在第一行:

       1,函数open() 打开文件

              对文件做任何操作的之前,首先必须打开文件

              在open()函数中指定文件名代表在当前目录寻找此文件,如果当前目录没有次文件会报错

    [root@Python-Test Alben-PY]# mv pi.txt pi_10.txt
    [root@Python-Test Alben-PY]# ./read_pi.py
    Traceback (most recent call last):
    File "./read_pi.py", line 4, in <module>
    with open('pi.txt') as file_object:
    FileNotFoundError: [Errno 2] No such file or directory: 'pi.txt'

       2,关键字 “with”

             函数open()的对应函数close()是指关闭文件,如果这样调用的话,在程序运行过程中如果遇到bug,导致close()未执行,

             导致文件不会关闭。未妥地关闭文件可能导致数据丢失或者受损。如果在程序中过早的调用close(),则可能导致需要再次

             使用文件时,文件已经关闭。

             使用“with”让python自动判断何时需要关闭文件。

     第二行,对打开的文件使用read()函数,读取的内容存放在变量 contents中。

    读取的效果:

    [root@Python-Test Alben-PY]# ./read_pi.py
    3.141592
    65358979
    32384626
    43383279

    [root@Python-Test Alben-PY]#

    源文件:

    [root@Python-Test Alben-PY]# cat pi.txt
    3.141592
    65358979
    32384626
    43383279
    [root@Python-Test Alben-PY]#

    可以发现末尾多了一行空行!

    why?
     因为read()到达文件尾部后会返回一个空字串,而将这个空字符串显示出来就是一个空行。

    如何删除:

    with open('pi.txt') as file_object:
    contents = file_object.read()
    print(contents.rstrip())

    效果:

    [root@Python-Test Alben-PY]# ./read_pi.py
    3.141592
    65358979
    32384626
    43383279
    [root@Python-Test Alben-PY]#

    2、文件路径

    读取文件的时候,如果文件不在当前目录下,需要制定路径

    例如:

    在/tmp下有一个文件,test1.txt

    [root@Python-Test Alben-PY]# cat /tmp/test1.txt
    this is test file
    please read thie file with python!

    如何读取此文件——

    #!/usr/bin/env python

    #filename = tmp_file.py

     

    with open('/tmp/test1.txt') as file_object:

        file_content = file_object.read()

        print(file_content.rstrip())

    这里的文件路径,可以用绝对路径,也可以用相对路径(linux文件路径基础有解释绝对与相对)

    note:如果是windows的话,目录分隔符是“”。

    3、逐行读取:

    需要查找文件特定内容的时候,就需要一行一行遍历文件,对文件逐行读取需要使用for循环

    例如,逐行读取/etc/passwd文件

    #!/usr/bin/env python

    #filename etc_passwd.py  

    filename = '/etc/passwd'   把文件路径定义到变量 filename

    with open(filename) as file_object:

        for line in file_object:    对打开的文件进行for循环

            print(line)

            if 'halt' in line:        当读取到的行中含有字符“halt”时,

                break                  中断循环

    效果:

    [root@Python-Test Alben-PY]# ./etc_passwd.py
    root:x:0:0:root:/root:/bin/bash

    bin:x:1:1:bin:/bin:/sbin/nologin

    daemon:x:2:2:daemon:/sbin:/sbin/nologin

    adm:x:3:4:adm:/var/adm:/sbin/nologin

    lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

    sync:x:5:0:sync:/sbin:/bin/sync

    shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown

    halt:x:7:0:halt:/sbin:/sbin/halt

    [root@Python-Test Alben-PY]#

    也会带有很多空格,使用相同的方法进行去除空格:

    with open(filename) as file_object:

        for line in file_object:

            print(line.rstrip())

            if 'halt' in line:

                break

    4、读取内容到列表

    使用‘with’时,open()返回的文件对象旨在with代码内可用,如果需要在with代码块外访问文件的内容,

    可在with代码块内讲文件的各行储存在一个列表中。

    例如:

    with open('pi.txt') as file_object:

        pi_list = file_object.readlines()

       

    print(pi_list)

    [root@Python-Test Alben-PY]# ./list_pi.py
    ['3.141592 ', '65358979 ', '32384626 ', '43383279 ']

    解读:

    因为readlines()读取文件的时候把文件夹末尾的换行符也读取进来了,所以生成的表格会带有 。

    处理这个列表:

    pi_string = ''

    for line in pi_list:

        pi_string += line.rstrip()

    print(pi_string)

    print(len(pi_string))

    在第一行,我们定义了一个空字符串 pi_string

    第二行使用for循环遍历这个列表,

    第三行把每一行去除结尾换行符后的内容添加到变量pi_string中

    最后打印变量 pi_string,同时计算len

  • 相关阅读:
    HDU 6071
    HDU 6073
    HDU 2124 Repair the Wall(贪心)
    HDU 2037 今年暑假不AC(贪心)
    HDU 1257 最少拦截系统(贪心)
    HDU 1789 Doing Homework again(贪心)
    HDU 1009 FatMouse' Trade(贪心)
    HDU 2216 Game III(BFS)
    HDU 1509 Windows Message Queue(队列)
    HDU 1081 To The Max(动态规划)
  • 原文地址:https://www.cnblogs.com/alben-cisco/p/6851402.html
Copyright © 2011-2022 走看看