# 三种写入文件测试

# 三种写入文件测试

import os

txt = 'hello \nworld'
file = '../demo.txt'
# dir = os.path.dirname(file)   # 如果路径中有不存在的子文件夹则创建
# if not os.path.exists(dir):
#     os.makedirs(dir)
# print(file)

# 第一种
with open(file, 'w') as f:
    f.write(txt)
    f.close()
    print('ok')
    os.system('notepad ' + file)
    
# 第二种
with open(file, 'a') as f:
    print(txt, file=f)
    f.close()
    print('okk')
    os.system('notepad.exe ' + file)

# 第三种
txt = 'helloooo'
command = f'echo {txt} >> {file}'     # 不能写多行文本
# command = f'echo {txt.strip()} >> {file}'
# command = f'echo {txt.strip()} >> "{file}"'
print(command)
os.system(command)
print('okkk')
os.system('notepad.exe ' + file)

 

posted @ 2025-01-07 15:03  nxhujiee  阅读(14)  评论(0)    收藏  举报