练习16--读写文件

一 相关知识点

1 需要记住的命令

  • close--关闭文件,就像编辑器中的”文件-->另存为“一样。
  • read--读取文件内容。你可以把读取结果赋给一个变量。
  • readline--只读取文本文件的一行内容
  • truncate--清空文件。清空的时候要当心
  • write("stuff")--给文件写入一些“东西”。
  • seek(0)--把读写的位置移到文件最开头

2 相关问题

  • truncate() 对于'w' 参数来说是必须的的吗?是
  • 'w'到底是什么意思? 它真的只是一个有字符的字符串,来表示文件的一种模式。如果你用了'w' ,就代表你说“用 ‘write’ 模式打开这个文件。此外还有 'r' 表示 read 模式, 'a' 表示增补模式,后面还可能加一些修饰符(modifiers)。
  • 我能对文件使用哪些修饰符? 目前最重要的一个就是 + ,你可以用 'w+' , 'r+' 以及'a+' 。这样会让文件以读和写的模式打开,取决于你用的是那个符号以及文件所在的位置等。
  • 如果只输入 open(filename) 是不是就用 'r' ((读)模式打开? 是的,那是 open() 函数的默认值

二 代码

参考例子:

from sys import argv

# 利用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("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")
# target.write(line1 + '\n' + line2 + '\n' + line3 + '\n')

# 关闭文件
print("And finally,we close it.")
target.close()

运行结果:

PS E:\3_work\4_python\2_code\02_LearnPythonTheHardWay> python ex16.py test.txt
We're going to erasetest.txt.
If you don't want that,hit CTRL-C (^C).
If you do want that,hit RETURN.
?RETURN
Opening the file...
Truncating the file.Goodbye!
Now I'm going to ask you for three lines.
line 1:I
line 2:Love
line 3:You
I'm going to write these to the file.
And finally,we close it.
PS E:\3_work\4_python\2_code\02_LearnPythonTheHardWay>

课后习题:

from sys import argv

script,filename = argv

print(f"We're going to read{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,encoding = "utf-8")

# 读取文件
print("I'm going to read the file.")
print(target.read())

# 关闭文件
print("And finally,we close it.")
target.close()

执行结果:

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.
PS E:\3_work\4_python\2_code\02_LearnPythonTheHardWay> python ex16_1.py ex15_sample.txt
We're going to readex15_sample.txt.
If you don't want that,hit CTRL-C (^C).
If you do want that,hit RETURN.
?RETURN
Opening the file...
I'm going to read the file.
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
And finally,we close it.
PS E:\3_work\4_python\2_code\02_LearnPythonTheHardWay>

 

posted @ 2020-07-02 02:42  洛兰123  阅读(190)  评论(0编辑  收藏  举报