exercise 15

作者: 不娶名字 | 来源:发表于2017-12-31 21:05 被阅读0次
    # 从sys模块中导入argu功能
    from sys import argv
    
    # 解包,分别把输入值放入script和filename
    script, filename = argv
    
    令把文件对象赋值给txt
    txt = open(filename)
    
    # 输出
    print(f"Here's your file {filename}:")
    输出txt引用对象的内容
    print(txt.read())
    
    # 重复上面内容
    print("Type the filename again:")
    file_again = input(">")
    
    txt_again = open(file_again)
    
    print(txt_again.read())
    

    练习

    1. Above each line, write out in English what that line does.
    2. If you are not sure, ask someone for help or search online. Many times searching for “python3.6
      THING” will find answers to what that THING does in Python. Try searching for “python3.6 open.”
    3. I used the word “commands” here, but commands are also called “functions” and “methods.” You
      will learn about functions and methods later in the book.
    4. Get rid of the lines 10-15 where you use input and run the script again.
    5. Use only input and try the script that way. Why is one way of getting the filename better than
      another?
    6. Start python3.6 to start the python3.6 shell, and use open from the prompt just like in this
      program. Notice how you can open files and run read on them from within python3.6 ?
    7. Have your script also call close() on the txt and txt_again variables. It’s important to close
      files when you are done with them.

    答案

    print("输入文件名")
    filename = input(">")
    txt = open(filename)
    print(f"Here is your {filename}")
    print(txt.read())
    

    再次运行 python 在命令行下使用 open 打开一个文件,这种 open 和 read 的方法也值得一学。

    >python
    >print open("15.txt").read()
    

    1
    2
    两种方式输出都相同,即为文件中的内容

    This is stuff I typed into a file.
    It is really cool stuff.
    Lots and lots of fun to have in here.
    

    相关文章

      网友评论

        本文标题:exercise 15

        本文链接:https://www.haomeiwen.com/subject/pkuagxtx.html