python语法基础-文件操作-长期维护

###############    python-简单的文件操作  ###############

# python中文件的操作
# 文件操作的基本套路
# 1,打开文件,默认是是只读方式打开文件
# 2,读写文件,默认是从文件的开始读取数据,也就是读取文件的所有内容
# 3,关闭文件,文件必须要关闭,否则会造成系统资源消耗,而且户影响后续会文件的访问

# 常用方法:
# open
# write
# read
# close
# readline,这个什么时候用,

# 文件打开方式:
# 语法如下:open(文件名,读取方式)
# r,只读,这是默认打开方式
# w,只写,
# a,追加,
# r+,以读写方式打开,如果文件不存在,抛出异常
# w+,以读写方式打开,如果文件不存在,创建文件,
# a+,以读写方式打开,如果文件存在,指针放到文件末尾,如果文件不存在,创建文件,


def read(file):
    file=open(file,'r')
    text=file.read()
    print(text)
    file.close()

def write(file):
    file=open(file,'w+') file.write('12345') file.close() def add(file): file=open(file,'a+') file.write('12345') file.close() def write_big_text(file): # 读取大文件 # 打开 file = open(file, 'r') # 读取 while True: text=file.readline() print(text,end='') # 读取每一行的末尾默认已经有了一个'\n' if not text: break # 关闭  file.close() def copy_file_small(file): # 小文件的复制 # 打开文件 file = open(file,'r') file2 = open('text2.txt', 'w+') # 读取,写入文件 text=file.read() file2.write(text) # 关闭文件  file.close() file2.close() def copy_file_big(file): # 大文件的复制 # 打开文件 file = open(file,'r') file2 = open('text3.txt', 'w+') # 读取,写入文件 while True: text=file.readline() if not text: break file2.write(text) # 关闭文件  file.close() file2.close() # 使用open每次都要关闭,太麻烦,而且会影响文件的后续操作,所以最常用的还是使用with打开文件,这样就不用调用close方法了, def open_with(file): with open(file,'r') as f: text=f.read() print(text) file='./test.txt' open_with(file)

使用try ... except来打开文件

def open_file(file):
    try:
        with open(file,'r') as f :
            text=f.read()
            print(text)
    except FileNotFoundError: print('文件不存在') except Exception as result: print('未知错误%s'%result) file = '123.txt' open_file(file)

猜你喜欢

转载自www.cnblogs.com/andy0816/p/12289720.html