15 阅读文件
from sys import argv
script, filename = argv
txt = open(filename)
print(f"Here's your file {filename}:")
print(txt.read())
print("Type the filename again:")
file_again = input(">")
txt_again = open(file_again)
print(txt_again.read())
takekensakai@Starrys-MacBook-Pro 笨方法学python3 % python3 15.py ex15_sample.txt
Here's your file 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.
Type the filename again:
>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.
16 读写文件
close - 关闭文件
truncate - 清空文件。清空的时候要当心。truncate() 对于 'w' 参数来说是必须的!!!
我能对文件使用哪些修饰符?目前最重要的一个就是 + ,你可以用 ‘w+’ , ‘r+’ 以及 ‘a+’ 。这样会让文件以读和写的模式打开,取决于你用的是那个符号以及文件所在的位置等。
write('stuff') - 给文件写入一些“东西”。
write 命令需要你提供一个你要写入的文件的字符串参数。