#文件的读写模式,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()
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。