发布于2020-03-17 16:19 阅读(2299) 评论(0) 点赞(4) 收藏(2)
【交作业啦】
ex16.py
# 从sys软件包中读取argv特性
from sys import argv
# 需要从命令行获取两个参数
script, filename = argv
# f-string
print(f"We are going to erase {filename}.")
print("If you don't want that hit CTRL-C (^C).")
print("If you do want that hit RETURN.")
input('?')
print("Opening the file...")
# 用只写的方式打开文件,返回文件对象,此文件对象不能read,只能write
target = open(filename, 'w')
print("Truncating the file. Goodbye!")
target.truncate()
print("Now I'm going to ask you for three lines.")
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
print("I'm going to write these to the file..")
print("First time...")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("Second time...")
fline = f"{line1}\n{line2}\n{line3}\n"
target.write(fline)
print("Third time...")
line = "{}\n{}\n{}\n"
target.write(line.format(line1,line2,line3))
print("And finally, we close it.")
target.close()
会话
PS E:\lpthw> python ex16.py test.txt
We are going to erase test.txt.
If you don't want that hit CTRL-C (^C).
If you do want that hit RETURN.
?
Opening the file...
Truncating the file. Goodbye!
Now I'm going to ask you for three lines.
line 1: hello
line 2: how are you
line 3: fine, thank you
I'm going to write these to the file..
First time...
Second time...
Third time...
And finally, we close it.
PS E:\lpthw>
巩固练习
2 使用read和argv读取新建的文件
ex16_ex.py
from sys import argv
script, filename = argv
txt = open(filename)
print(f"Here is your file {filename}: ")
print(txt.read())
print("Now we close it.")
txt.close()
会话
PS E:\lpthw> python ex16_ex.py test.txt
Here is your file test.txt:
hello
how are you
fine, thank you
hello
how are you
fine, thank you
hello
how are you
fine, thank you
Now we close it.
PS E:\lpthw>
【学习心得】
1 文件访问模式是“w”时,只允许写入,不允许读取
作者:74873487
链接:https://www.pythonheidong.com/blog/article/263325/3c495a9a3841267d4d7a/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!