笨方法学python 习题15

这篇博客介绍了Python中如何使用`sys.argv`读取文件,包括打开、读取文件内容并进行注释,以及利用`input`函数让用户交互式输入文件名再次读取。文章通过示例代码展示了文件处理的基本步骤,并强调了处理文件时需要注意的细节,以防止数据丢失或文件损坏。

学习目标:

处理文件需要非常仔细,如果不仔细可能会把文件弄坏或清空
用脚本“打开”文件,然后将其打印出来

代码如下

from sys import argv
#调用sys模块的argv函数
scripts,filename = argv,'ex15_sample.txt'
#参数命名,如果不命名filename参数,就无法读取txt
txt = open(filename)
#命名变量txt是打开打开filename,而filename的参数是'ex15_sample.txt'
print(f"Here's your life{filename}:")
#用(f'')显示字符串时,将把每个变量都替换为其值,替换值:{filename}
print(txt.read())
#read函数可以读取txt文件
print("Type the filename again:")
file_again = input(">")
txt_again = open(file_again)
#again函数,没查到怎么用,估计就是重复一下的意思喽
print(txt_again.read())

结果输出

Here's your lifeex15_sample.txt:
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
Type the filename again:
>ex15_sample.txt
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.

进程已结束,退出代码0

巩固练习:

1. 每行进行注释

2. 删掉10-15行,结果:

Here's your life ex15_sample.txt:
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.

3. 用input函数读取文件名

from sys import argv
scripts,filename = argv,'ex15_sample.txt'
txt = open(filename)
print('input type = "ex15_sample.txt"')

print(f"Here's your life {filename}:")
print(txt.read())
print("Type the filename again:")
file_again = input(">")
txt_again = open(file_again)
print(txt_again.read())

结果输出

input type = "ex15_sample.txt"
Here's your life ex15_sample.txt:
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
Type the filename again:
>ex15_sample.txt
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.

进程已结束,退出代码0

4. 读取文件相关的函数

在这里插入图片描述

Tips:

  1. 文件内容与文件对象
txt = open(filename)
#返回的是文件的内容吗?不是
#返回的是文件对象(file object)
  1. python不会限制打开了几次文件,有时候打开多次文件也是必需的。
from sys import argv
#是什么意思?
#sys是个软件包,从软件包提取argv这个特性
script, ex15_sample.txt = argv
#这样不灵,是错的
#需要命名文件名字,而不是直接放进去
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值