美文网首页Learn to Code
《笨办法学Python3》练习十五:读取文件

《笨办法学Python3》练习十五:读取文件

作者: 雨开Ame | 来源:发表于2019-03-02 00:15 被阅读0次

    练习代码

    from sys import argv
    
    script, filename = argv
    
    txt = open(filename)
    
    print(f"Here's your file {filename}")
    print(txt.read())
    
    print("Type the filename again:")
    file_again = input("> ")
    
    txt_again = open(file_again)
    
    print(txt_again.read())
    

    Study Drills

    1. Above each line, comment out in English what that line does.
    #  从sys模块中导入argv
    from sys import argv
    
    # 拆包argv,把其中值对应赋给script,filename变量
    script, filename = argv
    
    # 打开文件名为filename的值的文件,将文件流赋给名为txt的变量
    txt = open(filename)
    
    # 打印语句,打印文件流内容
    print(f"Here's your file {filename}")
    print(txt.read())
    
    # 打印语句,提示用户输入新文件名,用file_again存储文件名
    print("Type the filename again:")
    file_again = input("> ")
    
    # 打开文件,同上
    txt_again = open(file_again)
    
    # 打印文件流内容
    print(txt_again.read())
    
    1. 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.”

    2. 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.

    3. Get rid of lines 10–15 where you use input and run the script again.

    4. Use only input and try the script that way. Why is one way of getting the filename better than another?

    5. 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?

    6. 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.

    补充

    1. 始终记住是open read close的顺序。

    2. txt变量并不是存储文件内容,而是一个fileObject,具体后文再谈。

    3. Python并不限制文件的打开次数。

    相关文章

      网友评论

        本文标题:《笨办法学Python3》练习十五:读取文件

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