笨方法python3_“笨方法”学Python3,习题 15 。

928fb284243cfc94a2aaa29deb839f35.png

笨方法”学Python3,习题 15:读取文件

1、 如何用Python读取文件?

一、基础代码

1、 写脚本ex15.py

2、 创建文本txtx.txt(书上是ex15_sample.txt)

3、 执行代码,在终端输入:

325a91df37ed626a2aab357dc6a6b6a7.png
所写的代码:
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.

1ab54bf5b755d2d0a1af5a81c0bcbfd2.png

二、巩固练习

1、添加注释

0f0a153f82d8055f5c72fdcda11a594c.png
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.

7f74badb7cf46b86385b4344983ca218.png
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 ^,知乎此系列文章内容均会在微信公众号中同步更新,公众号:小民有个小旮旯

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值