学习目标:
处理文件需要非常仔细,如果不仔细可能会把文件弄坏或清空
用脚本“打开”文件,然后将其打印出来
代码如下
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:
- 文件内容与文件对象
txt = open(filename)
#返回的是文件的内容吗?不是
#返回的是文件对象(file object)
- python不会限制打开了几次文件,有时候打开多次文件也是必需的。
from sys import argv
#是什么意思?
#sys是个软件包,从软件包提取argv这个特性
script, ex15_sample.txt = argv
#这样不灵,是错的
#需要命名文件名字,而不是直接放进去
这篇博客介绍了Python中如何使用`sys.argv`读取文件,包括打开、读取文件内容并进行注释,以及利用`input`函数让用户交互式输入文件名再次读取。文章通过示例代码展示了文件处理的基本步骤,并强调了处理文件时需要注意的细节,以防止数据丢失或文件损坏。

1235

被折叠的 条评论
为什么被折叠?



