python文件的读写
发表于:2024-11-24 作者:热门IT资讯网编辑
编辑最后更新 2024年11月24日,#文件的读写模式,r w x a b t +def read_file():text = 'test.text'with open(text,encoding='utf-8') as
#文件的读写模式,r w x a b t +
def read_file():
text = 'test.text'
with open(text,encoding='utf-8') as r:#自动关闭文件,可以使用完全路径
rest = r.read()#将对象读取成为文件
readline只读一行
readlines读取所有行 以列表形式出现
print(rest)
if name=='main':
read_file()
#文件的写入def write_file():#逐个写入 file_name = 'test1' f = open(file_name,'w')#以写入的方式打开文件 f.write('hello') f.write('\n') f.write('world')def write_mult_line():#一次性写入 file_name = 'write_mult_line.txt' with open(file_name,'w',encoding='utf-8') as f: l = ['1','2','3'] f.writelines(l)def write_user_log():#随机记录时间和用户并且逐行写入 rest = '用户:{0} - 访问时间{1}'.format(random.randint(1000,9999), datetime.now()) print(rest) file_name = 'write_user_log.txt' with open(file_name,'a',encoding='utf-8') as f: f.write(rest) f.write('\n')def read_and_write():#先读再写入 判断是否有某个字符串 file_name = 'read_and_write' #这个需要先建立文件夹 with open(file_name,'r+',encoding='utf-8') as f: read_rest = f.read() if '1' in read_rest: f.write('kkkkkkkk') else: f.write('aaaa') f.write('\n')if __name__ == '__main__': read_and_write()