*笨办法学python3 学习笔记 习题14-16

这篇博客主要介绍了Python3中文件读取的相关知识,包括习题15的ex15_sample.txt内容的输出,open()函数的使用,以及read()函数的语法和功能。博主探讨了在Python环境下如何正确打开和读取文件,强调了文件关闭的重要性,并对习题16的读写文件操作进行了讲解,提出使用write()函数简化代码的建议。
摘要由CSDN通过智能技术生成

习题14

from sys import argv

script, user_name, age = argv
prompt = "Your answer: "

print(f"Hi {user_name}, I'm the {script} script.")
print("I'd like to ask you a few questions.")

print(f"Do you like me {user_name}?")
likes = input(prompt)

print(f"Where do you live {user_name}?")
lives = input(prompt)

print("What kind of computer do you have?")
computer = input(prompt)

print(f"""
Alright, so you said {likes} about liking me.
You live in {lives}.    Not sure where that is.
You are {age} years old now.
And you have a {computer} computer.     Nice.
""")
PS D:\pythonp> python .\ex14.py h 24
Hi h, I'm the .\ex14.py script.
I'd like to ask you a few questions.
Do you like me h?
Your answer: y
Where do you live h?
Your answer: C
What kind of computer do you have?
Your answer: m

Alright, so you said y about liking me.
You live in C.    Not sure where that is.
You are 24 years old now.
And you have a m computer.     Nice.


习题15 读取文件


# 将sys模块导入
from sys import argv

# 将argv解包,将所有的参数依次赋值给左边的变量
script, filename = argv

# 打开filename文件,并将该文件赋值给txt
txt = open(filename)

# 打印格式化字符串,“这是你的文件xxx:”
print(f"Here's your file {filename}:")
# 读取并打印txt的全部内容
print(txt.read())

# 打印“再次输入文件名”
print("Type the filename again")
# 打印“>”符号,并将输入的内容赋值给file_again
file_again = input(">")

# 打开file_again文件,并将文件赋值给txt_again
txt_again = open(file_again)

# 读取并打印txt_again的全部内容
print(txt_again.read())

ex15_sample.txt内容

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

输出结果

PS D:\pythonp> python ex15.py ex15_sample.txt
Here's your file ex15_sample.txt:
This is stuff I typed into a file.
It is really a cool stuff.
Lots and lots fun to have in here.

Type the filename again
>ex15_sample.txt
This is stuff I typed into a file.
It is really a cool stuff.
Lots and lots fun to have in here.
  1. 删掉第10~15行用到 input的部分,再运行一遍脚本。
from sys import argv

script, filename = argv

txt = open(filename)

print(f"Here's your file {filename}:")
print(txt.read())

                
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值