欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python 文件写入

程序员文章站 2024-01-01 19:08:40
def write_file(): """ 文件写入""" file_name = "wri2te_test.txt" # 以写入的方式打开 f = open(file_name,'w') # 写入内容 f.write('hello') # 换行符 f.write('\n') # 写入内容 f.wr ......

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()

上一篇:

下一篇: