笨方法自学python(九)-读写文件

读取文件

前面已经学过了 input 和 argv,这些是你开始学习读取文件的必备基础。你可能需要多多实验才能明白它的工作原理,这节练习涉及到写两个文件。一个正常的 ex15.py 文件,另外一个是 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.

我们要做的是把该文件用我们的脚本“打开(open)”,然后打印出来。
以下是ex15.py的程序

from sys import argv
script, filename = argv
txt = open(filename)
print("Here's your file %r:"%filename)
print(txt.read())
print("Type the filname again:")
file_again = input(">")
txt_again = open(file_again)
print(txt_again.read())

运行结果:

在这里插入图片描述

读写文件

需要记住以下命令:

  1. close – 关闭文件。跟你编辑器的 文件->保存… 一个意思。
  2. read – 读取文件内容。你可以把结果赋给一个变量。
  3. readline – 读取文本文件中的一行。
  4. truncate – 清空文件,请小心使用该命令。
  5. write(stuff) – 将 stuff 写入文件。

例题:

from sys import argv

script,filename = argv

print("we're going to erase %r." %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")
print("And finally,we close it.")
target.close()

运行结果:
line1,line2,line3后面是我们自己输入的,运行完毕后打开 test.txt看看里面是什么
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值