习题15:读取文件

发布时间:2017-11-10 15:50:38编辑:Run阅读(3780)

    代码如下

    # coding: utf-8
    __author__ = 'www.py3study.com'
    from sys import argv
    script, filename = argv
    txt = open(filename)
    print("Here's you file {}:".format(filename))
    print(txt.read())
    print("Type the filename again:")
    file_again = input(">>")
    txt_again = open(file_again)
    print(txt_again.read())

    这个脚本中有一些新鲜的玩意,快速的讨论一下

    使用argv来获取文件名,open打开一个文件,txt.read()读取文件的内容

    首先在当前路径创建一个ceshi.txt文件(跟脚本文件是在同一个目录下)

    ceshi.txt里面写入www.py3study.com,保存,输入命令运行程序

    python lianxi_15.py ceshi.txt

    应该看到的结果

    E:\test>python lianxi_15.py ceshi.txt
    Here's you file ceshi.txt:
    www.py3study.com
    Type the filename again:
    >>ceshi.txt
    www.py3study.com

    常见问题

    txt = open(filename)返回的是文件内容吗?

    不是,它返回的是一个叫做"file object"的东西,你可以随意访问内容的任意位置,并且去读取这种内容,不过object本身并不是它的内容

    from sys import argv是什么意思?

    sys是一个代码块,这句话的意思是从代码库取出argv这个功能,后面的练习会学到很多

    为什么打开了两次文件没有报错?

    Python不会限制你打开文件的次数,事实上有时候多次打开一个文件是一件必须的事情



关键字