from sys import argv
script, filename = argv
txt = open(filename) #打开文件
print ("Here's your file %r:" % filename)
print (txt.read()) #对文件进行读操作
txt.close() #关闭文件
print ('-' * 15)
print ("provide a file to read!")
filename = input("Type File Name: ")
txt = open(filename)
print (txt.read())
txt.close()
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.
---------------
provide a file to read!
Type File Name: 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.
#close---close file
#read---read file content
#readline---read line
#truncate---clear up file
#write(stuff)---write stuff into file
from sys import argv
script, filename = argv
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("?")
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") #写入换行符
print ("And finally, we close it.")
target.close() #关闭文件
print ("Open a file.")
filename = input(":\\")
txt = open(filename,'r')
print (txt.read())
txt.close()
调用命令:
python .\ex16.py .\ex16.txt
We're going to erase '.\\ex16.txt'.
If you don't want that, hit CTRL-C (^C).
If you do want that, hit RETURN.
?f
Opening the file...
Truncating the file. Goodbye!
Now I'm going to ask you for three lines.
line 1: da
line 2: fd
line 3: ew
I'm going to write these to the file.
And finally, we close it.
Open a file.
:\ex16.txt
da
fd
ew