“笨办法”学Python3--习题16 读写文件

 读写文件 (写入w、读取r、追加a)Python3

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.")
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("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")

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")

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

 文件相关命令

  1. close:关闭文件。
  2. read:读取文件,把结果赋给一个变量
  3. readline:只读取文本文件的一行
  4. truncate:清空文件
  5. write(‘stuff’):将stuff写入文件
  6. seek(0):将读写位置移动到文件开头

readline() 方法语法如下:

fileObject.readline()

readline() 方法用于从文件读取整行,包括 "\n" 字符。如果指定了一个非负数的参数,则返回指定大小的字节数,包括 "\n" 字符。

open的参数

target = open(filename, 'w') #以写入模式打开文件

  • ‘w’--write写入模式
  • ‘r’--read读取
  • ‘a’--append追加
  • 可以使用加号修饰符+:‘w+’,‘r+’,‘a+’;可以把文件同时以读写方式打开
  • open默认为‘r’

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值