笨方法”学Python3,习题 15:读取文件
1、 如何用Python读取文件?
一、基础代码
1、 写脚本ex15.py
2、 创建文本txtx.txt(书上是ex15_sample.txt)
3、 执行代码,在终端输入:
所写的代码:
from sys import argv
script, filename = argv
txt = open(filename)
print(f"Here's your file {filename}:")
print(txt.read())
print("Type the filename again:")
file_again = input("> ")
txt_again = open(file_again)
print(txt_again.read())
---------------------------------------------------------------------------------------------------
应该看到的结果:
PS D:代码> & D:/软件/python/python.exe d:/代码/ex15.py txtx.txt
Here's your file txtx.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:
> txtx.txt
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
二、巩固练习
1、添加注释
2、内置函数(open、read、write、close)
file = open("文件名","访问方式") # open打开文件并返回文件对象,文件不存在则抛出异常
file.read() # 读操作
file.write() # 写操作
file.close() # 负责关闭文件
5、用input写脚本。个人认为argv更好,两者的区别是用户输入的时机不同。如果参数是在用户执行命令时就要输入,那就是 argv ;如果是在脚本运行过程中需要用户输入,那就使用input。
所写的代码:
filename = input("filename?")
txt = open(filename)
print(f"Here's your file {filename}:")
print(txt.read())
print("Type the filename again:")
file_again = input("> ")
txt_again = open(file_again)
print(txt_again.read())
---------------------------------------------------------------------------------------------------
应该看到的结果:
PS D:代码> & D:/软件/python/python.exe d:/代码/ps.py
filename?txtx.txt
Here's your file txtx.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:
> txtx.txt
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
7、调用close函数
from sys import argv # 从sys库中调用argv
script, filename = argv # 定义变量
txt = open(filename) # 打开filename变量对应的文件并赋值给变量txt
print(f"Here's your file {filename}:")
print(txt.read()) # 读取txt的内容并打印
txt.close()
print("Type the filename again:")
file_again = input("> ") # 执行input函数,将输入内容赋值给变量file_again
txt_again = open(file_again) # 打开,赋值
print(txt_again.read()) # 读取,打印
txt_again.close()
总结:
1、可以将文件的内容通过函数赋值给变量,再针对变量进行操作,实现打印文件
2、open可以打开文件,read读取文件,write写文件,close关闭文件
^ v ^,知乎此系列文章内容均会在微信公众号中同步更新,公众号:小民有个小旮旯