一 相关知识点
1 需要记住的命令
2 相关问题
二 代码
参考例子:
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>
原文:https://www.cnblogs.com/luoxun/p/13222605.html