《Learn python3 the hard way》ex16 读写文件

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

from sys import argv #引入argv包

script, filename = argv #拆包一个script一个文件名

print(f"we're going to erase {filename}.") #打印格式化语句
print("If you don't want that, hit CRTL_C(^C).") #说明可以按crtl+c暂停程序
print("If you do want that,hit RETURN.") #打印说明按回车键是继续

input("?") #通过input输入用户选择的

print("Opening the file...") #提示
target = open(filename,'w') #打开文件,以写入的方式,open默认是读取所以要写入需修改

print("Truncating the file.Goodbye!") #提示
target.truncate() #清空文件

print("Now I'm going to ask you for three lines.")
#通过3次input将用户的语句赋值给3个变量
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()#关闭文件

猜你喜欢

转载自blog.csdn.net/qq_43181584/article/details/83511495
今日推荐