首页 > 编程语言 >【笨方法学python】ex16 - 读写文件

【笨方法学python】ex16 - 读写文件

时间:2022-10-05 06:11:05浏览次数:63  
标签:文件 target python ex16 write raw print input 方法学

代码如下:

点击查看代码
# -*-coding:utf-8- -*-
# 读写文件

# close - 关闭文件(保存)。
# read - 读取文件内容,结果可赋值给一个变量。
# readline - 读取文本文件中的一行。
# truncate - 清空文件。
# write(stuff) - 将 stuff 写入文件

# 编写一个文本编辑器
from sys import argv

script, filename = argv

print "We're going to earse %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename, "w+") # "w" 写入模式; "r" 读取模式; "a" 追加模式

print "Truncating the file. Goodbye!"
target.truncate() # 从当前位置截断。 括号里也可以加参数,表示从第几位开始截断。

print "Now I'm going to ask you for three lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_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()

执行结果:
image

标签:文件,target,python,ex16,write,raw,print,input,方法学
From: https://www.cnblogs.com/TiramisuPS/p/16754987.html

相关文章