写入文件
poem = "'\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
"'
f = file('poem.txt', 'w') #打开文件 r/w/a 读/写/追加
f.write(poem) #write text to file
f.close() #关闭
读取文件
f = file('poem.txt') #第二个参数没给,默认是r 读取
while True:
line = f.readline()
if len(line) == 0:
break
print line,
f.close()
with 语句
写入文件: #自动处理f.close()
with open('poem.txt', 'w') as f:
f.write(poem)
读取文件
with open('poem.txt') as f:
while True:
line = f.readline()
if len(line) == 0:
break
print line,