【argv】对文件的写入write

对txt文件进行写入

  写入之前需要对文件内容进行truncate擦除

  input 要写入的内容

  write进行写入操作

from sys import argv

# script是py文件,用于对txt文件
script, filename = argv

# 提示擦除filename里面的内容,
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("?")

# 使用truncate进行擦除
print("Opening the file...")
target = open(filename, 'w')
print("Truncating the file.Goodbye!")
target.truncate()

# line1,line2,line3用于接受你在cmd三次input
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.")

# 将line1,line2,line3 的内容写入到目标文件即刚才的filename中
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()

  cmd中:

python test.py start.txt

  结果如下:

 

posted @ 2022-06-10 00:26  淫鬻  阅读(19)  评论(0编辑  收藏  举报