码迷,mamicode.com
首页 > 编程语言 > 详细

python 文件写入

时间:2019-08-01 11:38:17      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:and   lines   from   bbb   user   log   mat   判断   random   


def write_file():
""" 文件写入"""
file_name = "wri2te_test.txt"
# 以写入的方式打开
f = open(file_name,‘w‘)
# 写入内容
f.write(‘hello‘)
# 换行符
f.write(‘\n‘)
# 写入内容
f.write(‘world‘)

# 关闭文件
f.close()

def write_mult_line():
""" 多行写入"""
file_name = ‘write_mult_line.txt‘
with open(file_name, ‘w‘, encoding = ‘utf-8‘) as f:
# \r\n 换两行
# \n 换一行
l = [‘第1行‘,‘\n‘,‘第2行‘,‘\r\n‘,‘第3行‘,‘\n‘,‘第4行‘]
f.writelines(l)


import random
from datetime import datetime
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 + ‘\n‘)


def read_and_write():
""" 先读,再写入"""
file_name = ‘read_and_write.txt‘
with open(file_name, ‘r+‘, encoding="utf-8") as f:
read_rest = f.read()
# 判断如果没有1 写一行 aaa
# 判断如果有1 写一行 bbb
if ‘1‘ in read_rest:
f.write(‘\n‘)
f.write(‘aaa‘)
else:
f.write(‘bbb‘)


if __name__ == ‘__main__‘:
# write_file()
# write_mult_line()
# write_user_log()
read_and_write()

python 文件写入

标签:and   lines   from   bbb   user   log   mat   判断   random   

原文地址:https://www.cnblogs.com/ericblog1992/p/11281432.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!