pythonファイルの基本処理
6526 ワード
一、ファイルのオープン
二、ファイルの読み取り
例:
三、ファイルの書き込みと書き込みキャッシュ
注意:
例:
五、osモジュールを使用してファイルを操作する
:open(name[,mode[buf]])
name:
mode:
buf: buffering
mode
r
w ,
a
r+/w+
a+
rb、wb、ab、rb+、wb+、ab+:
:
#
# f = open("hello.py")
# c = f.read()
# print c
#
# f = open('1.txt','w')
# f.write("test write")
# f.close()
#
# f = open("hello.py",'a')
# f.write("print 'write test'")
# f.close()
二、ファイルの読み取り
read([size]): ( size , )
readline([size]):
readlines([size]): ( ), ( )
iter:
例:
#
# f = open("1.txt")
# c = f.read()
# c = f.readline()
# c = f.readline(2)
# c = f.readlines()
# print c
#
# iter_f = iter(f)
# lines = 0
# for line in iter_f:
# lines += 1
#
# print lines
三、ファイルの書き込みと書き込みキャッシュ
write(str):
writelines(sequence_of_strings):
例:#
# f = open("test.txt",'w')
# f.writelines("123123123")
# f.writelines(('223','xczcxc','gfweqq'))
# f.flush() #
# f.close()
注意:
# 1、
# 2、linux
# 3、 ,
、
Python
seek(offset[,whence]):
offset:
whence: ;
Python
os.SEEK_SET:
os.SEEK_CUR:
os.SEEK_END:
例:
f = open("1.txt",'r+')
# f.tell() //
# f.read(3)
f.seek(-5,os.SEEK_END)
# f.read()
python
file.fileno() //
file.mode:
file.encoding:
file.closed:
五、osモジュールを使用してファイルを操作する
:
その他の操作方法:os.open(filename,flag[,mode]): flag: os.O_CREAT: os.O_RDONLY: os.O_WRONLY: os.O_RDWR: os.read(fd,buffersize): os.write(fd,str): os.lseek(fd,pos,how): os.close(fd):
access(path,mode) 、F_OK , : R_OK( ) 、W_OK( ) 、X_OK( ) listdir(path) remove(path) rename(old,new) mkdir(path,[,mode]) makedirs(path,[,mode]) removedirs(path) rmdir(path) ( )
:
fd = os.open("hello.txt",os.O_CREAT|os.O_RDWR) n = os.write(fd,"test write") l = os.lseek(fd,0,os.SEEK_SET) str = os.read(fd,5) os.close(fd)
os.path exists(path) isdir(s) isfile(path) getsize(filename) dirname(p) basename(p)