程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-06(4)

笨办法学Python 3 习题16

发布于2020-03-17 16:19     阅读(2141)     评论(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黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

4 0
收藏该文
已收藏

评论内容:(最多支持255个字符)