exercise 15

# 从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.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,916评论 0 23
  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的阅读 13,551评论 5 6
  • 1、注册 GitHub 账号, 把github用户名发送给老师carolinecjun , 已发给老师。2、看Gi...
    jirengu_cyj阅读 163评论 0 0
  • 时常感到无聊。 每到这时又甚是唾弃自己。看看周边的人,剪辑着喜爱的偶像的视频;画着脑海中的那逐渐清晰的图像;为获得...
    朔朔阅读 248评论 0 1
  • 体验 今天和国龙老师在客户家开启动会,切身体会到一个领袖的思维决定企业的发展速度。在产品同质化的时代,团队是核心竞...
    若兰ZHOU阅读 127评论 0 1