本讲要记住的以下几种与文件操作相关的命令:

  • close:关闭文件,类似于保存的意思。
  • read: 读取文件中的内容,将结果赋值给变量。
  • readline: 只读取文本文件中的一行。
  • truncate: 清空文件,请小心使用该命令。
  • write('stuff'):将“stuff”写入文件。
  • seek(0): 将读写位置移动到文件开头。

程序代码:


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


运行结果:


PS D:\lpthw> python ex16.py test.txt
We're going to erase test.txt.
If you don't want that, hit CTRL-C(^C).
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file. Goodbye!
Now I'm going to ask you for three lines.
line 1: Mary had a little lamb
line 2: It's fleece was white as snow
line 3: It was also tasty
I'm going to write these to the file.
And finally, We close it.
最后修改:2021 年 03 月 15 日
如果觉得我的文章对你有用,请随意赞赏