Python基础——如何使用文件及目录

来源:互联网 发布:淘宝赚佣金的手机软件 编辑:程序博客网 时间:2024/06/05 23:40

#!/usr/bin/python
# * coding: UTF-8 *

open a file

fo = open(‘fo.txt’,’wb’)
print fo.name #return the filename
print fo.closed #return a boolen if the file is closed.return ture
print fo.mode #return the file access mode
print fo.softspace #

write and read file

fo.write(“www.baidu.com “)
fo.write(“www.google.com”)

the file location

fo = open(‘fo.txt’,’r+’)
s1 = fo.read(10)
s2 = fo.read(10)
s3 = fo.read(10)
print s1
print s2
print s3
position = fo.tell()
print ‘now the file position is :’, position
fo.seek(0,0)
print fo.read(10)
print ‘now the file position is :’, fo.tell()
fo.close()

how to operate the file you should use the os moudle

import os #import os module

os.rename(‘fo.txt’,’foo.txt’) #rename file name

try:
foo = open(‘fo.txt’,’r+’)
#use try except to open the file if the file not exist throw the message
except:
print ‘the file not exsit’

remove the file

os.remove(‘fo.txt’)

how to operate the contents

print os.path.abspath(‘.’)

0 0
原创粉丝点击