python学习之路三(文件读写)

# -*- coding: utf-8 -* 
'''
Created on 2013-7-29

@author: lixingle
'''
import os  #引入操作文件和目录的函数包
import pickle
#数据持久化..................................................
#写入文件
fout=open('g://test.txt','w')#如果要写入第二个参数 要写‘w’
fout.write('你好吗?')
fout.write('好') #接着写
#格式输入,多个占位符时后面要跟一个元组
line='my name is %s age is %d'%('lixingle',22)
print line
fout.write('\n'+line) #接着写
#文件内如下:
#你好吗?好
#my name is lixingle age is 22

fout.close()#关闭文件

cwd=os.getcwd()
print cwd #D:\JAVATiku\SiYue\Python\PythonDemo\src\demos
print os.path.abspath('test.txt')#返回绝对路径
print os.path.isdir('test.txt')#False 判断是否为目录
#捕获异常......................................................
try:
    fop=open('g://test')
    for line in fop:
        print line
    fop.close()   
except:
    print 'Something went wrong'

#读取文件
try:
    fop=open('g://test.txt')
    line=fop.readline()#读取一行
    print line
    fop.close()   
except:
    print 'Something went wrong'
python学习之路三(文件读写)

你可能感兴趣的:(python)