Python学习笔记(笨方法学Python3)-习题16:读写文件

本文深入讲解了使用Python进行文件操作的基本方法,包括打开、读取、写入、清空及关闭文件等关键步骤。通过一个具体示例,演示了如何创建、编辑并管理文本文件,适合初学者和进阶开发者学习。

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

from sys import argv

script,filename = argv

print(f"we're going to erase {filename}.")
print("if you don't want that, hit CTRL-C(^c).")
print("if you do want that, hit return.")

input("?")

print("opening the file...")
target=open(filename, 'w')

print("truncating the file. Goodbye!")
target.truncate()

print("Now i'm going to ask you for three lines.")
line1=input('line1: ')
line2=input("line2: ")
line3=input("line3: ")

print("i'm going to write these to the file.")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

newlineall=line1+"\n"+line2 + "\n" + line3 + "\n"
target.write(newlineall) 

print("and finally, we close it.")
target.close()

结果为:
在这里插入图片描述
*close 关闭文件
*read 读取文件内容
*readline 只读取文本文件中的一行
*truncate 清空文件,请小心使用该文件
*write('stuff') 将stuff写入文件
*seek(0) 将读写位置移动到文件开头

*open多传入一个‘w’,open对文件的写入操作态度是安全第一,特别指定才能写入
*open默认为读取
*r 读取,w 写入,a 追加
*修饰符 + 'w+' 'a+' 'r+' 可以把文件同时用读写的方法打开

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值