
可以永久的保存数据.
⽂件在硬盘中存储的格式是⼆进制.
打开⽂件
读写⽂件
关闭⽂件
读⽂件-r#1.打开文件,是文件从硬盘中存到内存中
# open(file, mode='r' , encoding)
#file要 *** 作的文件名字,类型是str
# mode,文件打开的方式,r(read)只读打开,w(write)只写打开a(append)追加打开
# encoding文件的编码格式,常见的编码格式有两种,一种是gbk,一种是utf-8
#返回值,文件对象,后续所有的文件 *** 作,都需要通过这个文件对象进行
#以只读的方式打开当前目录中,1.txt 文件,文件不存在会报错
f = open('1.txt ' , 'r')
# 2.读文件文件对象.read( )
buf = f.read()
print(buf)
#3.关闭文件文件.cLose()将内存中三大文件同步到硬盘中f
.close()
写⽂件-w
# 1、打开文件w方式打开文件,文件不存在,会创建文件,文件存在,会覆盖清空原文件
f = open( 'a.txt', 'w ' , lencoding='utf-8")
#2.写文件文件对象.write(写入文件的内容)
f.write( ' he1lo wor1d ! n')
f.write( ' he1lo python! n')
f.write('你好,中国!')
#3.关闭文件
f.close()
追加⽂件-a
#a方式打开文件,追加内容,在文件的末尾写入内容 #文件不存在,会创建文件 #注意点:不管是a方式打开文件,还是w方式打开文件,写内容,都是使用 write()函数 f = open( 'b.txt' , 'a', encoding=' utf-8') # f. write( ' hello worLd ! n ' ) f.write( '111n') f.close()⽂件读 *** 作 read()
#1.打开文件 f = open( 'a.txt ' , 'r', encoding=' utf-8 ' ) #2.读写文件文件对象.read(n) n一次读取多少字节的内容,默认不写,读取全部内容 buf = f.read( 3) print(buf) # 123 print( ' -'*30) buf = f.read(3)#5 print(buf) #3.关闭文件 f.close()按⾏读取
f = open( 'a.txt ' , 'r', encoding= ' utf-8') #f. readline() #一次读取一行的内容,返回值是读取到的内容(str) # buf = f.readline() #f. neadLines() #按行读取,一次读取所有行,返回值是列表,列表中的每一项是一个字符串,即一行的内容 buf = f.readlines() print(buf) f.close()⽂件访问模式
import os
def create_files():
for i in range(10):
file_name = 'test/file_' + str(i) + '.txt'
print(file_name)
f = open(file_name,'w')
f.close()
def create_files_1():
os.chdir( 'test' )
for i in range(10,20):
file_name = 'file_' +str(i) + '.txt'
print(file_name)
f = open(file_name,'w ')
f.close()
os.chdir( '../')# ../ 上一级目录
def modify_filename( ) :
os.chdir( 'test ' )
buf_list = os.listdir( )
# print( buf_list)
for file in buf_list:
new_file = 'py43_'+ file
os.rename(file, new_file)
os.chdir( '../ ')
def modify_filename_1():
os.chdir( 'test' )
buf_list = os.listdir( )
# print( buf_list)
for file in buf_list:
num = len( ' py43_')
new_file = file[num : ]
os.rename(file, new_file)
os.chdir( ' ../ ')欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)