【Python文件新建、打开、读写、保存、查看信息操作】 1 指定格式打开文件 2 关闭文件 3 使用with语句保证新建、打开后关闭文件,避免异常 4 写入文件 5 使用with语句保证打开后关闭文件,避免异常 6 复制文件 7 移动文件 8 重名名 9 判断文件或文件夹是否存在 10 删除文件 11 获取文件基本信息
1 指定格式打开文件
import os, sys
file = open ( 'message.txt' , 'w' )
file = open ( 'message.txt' , 'r' , encoding= 'utf-8' )
2 关闭文件
file . close( )
3 使用with语句保证新建、打开后关闭文件,避免异常
with open ( 'message.txt' , 'w' ) as file : pass
4 写入文件
file = open ( 'message.txt' , 'w' , encoding= 'utf-8' ) file . write( '我是一个程序员,我有良好的编程习惯!\n' )
file . close( )
file = open ( 'message.txt' , 'a+' , encoding= 'utf-8' )
file . write( '我是一个老师1,我有喜欢教书!\n' )
file . close( )
5 使用with语句保证打开后关闭文件,避免异常
with open ( 'message.txt' , 'r' , encoding= 'utf-8' ) as file : print ( "============读取前5个字符==============" ) print ( file . read( 5 ) ) print ( "\n============读取第一行字符==============" ) print ( file . readline( ) ) print ( "\n============读取所有字符==============" ) print ( file . readlines( ) ) file . seek( 9 ) string = file . read( 5 ) print ( '\n' + string)
输出如下:
============读取前5个字符==============
我是一个程============读取第一行字符==============
序员,我有良好的编程习惯!============读取所有字符==============
['我是一个老师,我有喜欢教书!\n', '我是一个老师1,我有喜欢教书!\n']个程序员,
6 复制文件
import shutil
shutil. copyfile( './message.txt' , './message1.txt' )
'./message1.txt'
7 移动文件
shutil. move( './message.txt' , './data/message.txt' )
'./data/message.txt'
8 重名名
os. rename( 'message1.txt' , 'message2.txt' )
shutil. move( './message2.txt' , './message1.txt' )
'./message1.txt'
9 判断文件或文件夹是否存在
if not os. path. exists( './data/' ) : os. mkdir( './data/' ) if not os. path. exists( './message1.txt' ) : with open ( 'message.txt' , 'w' ) as file : pass
10 删除文件
os. remove( './message1.txt' )
11 获取文件基本信息
os. stat( './data/message.txt' )
os.stat_result(st_mode=33206, st_ino=2251799814167302, st_dev=854872561, st_nlink=1, st_uid=0, st_gid=0, st_size=191, st_atime=1691328797, st_mtime=1691328772, st_ctime=1691328768)
import time, os
fileinfo = os. stat( './data/message.txt' )
print ( '文件路径:' + os. path. abspath( './data/message.txt' ) + "\n文本大小:" + str ( fileinfo. st_size) + "字节" + "\n最后一次访问时间:" + time. strftime( '%Y-%m-%d %H:%M:%S' , time. localtime( fileinfo. st_atime) ) + "\n最后一次修改时间:" + time. strftime( '%Y-%m-%d %H:%M:%S' , time. localtime( fileinfo. st_mtime) ) + "\n最后一次状态变化时间:" + time. strftime( '%Y-%m-%d %H:%M:%S' , time. localtime( fileinfo. st_ctime) ) )
文件路径:........\data\message.txt
文本大小:191字节
最后一次访问时间:2023-08-06 21:33:17
最后一次修改时间:2023-08-06 21:32:52
最后一次状态变化时间:2023-08-06 21:32:48