Python学习9-读写文件

上一篇 / 下一篇  2014-06-25 15:45:37 / 个人分类:笨办法学Python

$ex15.py 源码
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()

调用命令:
python .\ex15.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.


---------------
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.

使用pydoc open查看open的使用方法
  • close – 关闭文件。跟你编辑器的 文件->保存.. 一个意思。
  • read – 读取文件内容。你可以把结果赋给一个变量。
  • readline – 读取文本文件中的一行。
  • truncate – 清空文件,请小心使用该命令。
  • write(stuff) – 将stuff写入文件。
$ex16.py 源码
#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


TAG:

 

评分:0

我来说两句

Open Toolbar