如何使用 UliEngineering 在 Python 中写入文本文件

你可以使用 UliEngineering Python 库轻松将文本内容写入文件:

write_textfile.py
from UliEngineering.Utils.Files import write_textfile
import tempfile
import os

# 创建一个临时文件路径
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt') as f:
    temp_file = f.name

# 将内容写入文件
write_textfile(temp_file, "Hello, World!\nThis is a test file.")

# 读回内容以验证
with open(temp_file, 'r') as f:
    content = f.read()
    print(content)

# 清理
os.unlink(temp_file)

示例输出

write_textfile_output.txt
Hello, World!
This is a test file.

该函数将提供的字符串内容写入文件,自动处理文件创建和正确的编码。它是写入文本文件的便捷封装,具备完善的错误处理。适用于保存配置文件、日志条目或任何基于文本的数据输出。

相关文章


Check out similar posts by category: Python, File I/O