《笨》练习 15阅读文件、16读写文件

这篇博客介绍了Python中对文件进行读写的基本操作,包括使用'w+'、'r+'和'a+'等模式。文章通过示例展示了如何打开、读取、重写和追加文件内容,并强调了`close()`和`truncate()`方法的重要性。同时,提到了`write()`函数用于向文件写入字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

15 阅读文件

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())
takekensakai@Starrys-MacBook-Pro 笨方法学python3 % python3 15.py ex15_sample.txt
Here's your file 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.

16 读写文件

close - 关闭文件
truncate - 清空文件。清空的时候要当心。truncate() 对于 'w' 参数来说是必须的!!!


我能对文件使用哪些修饰符?目前最重要的一个就是 + ,你可以用 ‘w+’ , ‘r+’ 以及 ‘a+’ 。这样会让文件以读和写的模式打开,取决于你用的是那个符号以及文件所在的位置等。

write('stuff') - 给文件写入一些“东西”。
write 命令需要你提供一个你要写入的文件的字符串参数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值