文件的打开与关闭
相对路径 open
file_open = open ( '.点(文件)' ) 同级目录
file_open = open ( '../' ) 上级目录
绝对路径
打开文件- - - -
操作文件
print ( file_open. read( 4 ) )
print ( len ( file_open. read( 4 ) ) )
关闭文件close( )
print ( file_open. close( ) )
文件访问模式
r
file_open = open ( '.点(文件)' , 'r' , encoding= 'utf8' )
file_1 = file_open. read( )
a
file = open ( 'zheng.txt' , 'a' , encoding= 'utf8' )
file . write( '我爱小玉' )
w 写入
file_open = open ( '.点(路径)' , 'w' , encoding= 'utf8' )
file_1 = file_open. write( )
r+
file_open = open ( '.' , 'r+' , encoding= 'utf8' )
file = open ( 'zheng.txt' , 'r+' , encoding= 'utf8' )
file . write( '我爱小玉' )
w+ w
a+
file = open ( 'zheng.txt' , 'a+' , encoding= 'utf8' )
file . write( '我爱小玉' ) 写入文件
rb+
wb+
ab+
读取写入文件相关操作
tell
print ( file_open. tell( ) )
seek
file_open. seek( 0 )
print ( file_open. read( ) )
flush( )
close( )
read( )
file = open ( 'zheng.txt' , 'r' , encoding= 'utf8' )
print ( file . read( ) )
readline( )
file = open ( 'zheng.txt' , 'r' , encoding= 'utf8' )
print ( file . readline( ) )
readlines( )
file = open ( 'zheng.txt' , 'r' , encoding= 'utf8' )
print ( file . readlines( ) )
writelines( )
seek坑点
seek( offset, from )
在文本文件中,没有使用b模式选项打开的文件,只允许从文件开头开始计算相对位置,从文件尾计算时就会引发异常
例
123456789
seek( 4 , 0 )
seek( 4 , 1 )
seek( 4 ,2 )
os模块的目录及文件操作
import os
print ( os. getcwd( ) )
print ( os. getcwd( ) )
print ( os. listdir( ) )
print ( os. chdir)
print ( os. mkdir( 'wixy' ) )
print ( os. rmdir( 'wixy' ) )
print ( os. system( 'tree' ) )
print ( os. rename( 'old' , 'new' ) )
os.path模块操作
print ( os. path. join( 'zwm1' , 'zwn.txt' ) )
print ( os. path. basename( 'zwm.txt' ) )
print ( os. path. abspath( 'zwm.txt' ) )
print ( os. path. relpath( ) )
print ( os. path. getsize( 'zwm.txt' ) )
print ( os. path. getctime( 'zwm.txt' ) )
print ( os. path. getmtime( 'zwm.txt' ) )
print ( os. path. getatime( 'zwm.txt' ) )
print ( os. path. exists( 'zwm.txt' ) )
print ( os. path. isdir( '..\zwm1' ) )
print ( os. path. isfile( 'zwm.txt' ) )
print ( os. path. isabs( 'zwm\zwm.txt' ) )
上下文管理器
with open ( ) as file :
例:
with open ( 'zwm.txt' , 'w' , encoding= 'utf8' ) as file , \
open ( 'zwm1.txt' , 'w' , encoding= 'utf8' ) as file1, \
open ( 'zwm2.txt' , 'w' , encoding= 'utf8' ) as file2, \
open ( 'zwm3.txt' , 'w' , encoding= 'utf8' ) as file3:
file . write( 'wixy' )
file1. write( 'wixy' )
file2. write( 'wixy' )
file3. write( 'wixy' )
导自定义函数路径问题
import sys
print ( sys. path( ) )
from z. z import name
print ( name)
sys. path. append( )