本文共 687 字,大约阅读时间需要 2 分钟。
最直接的方法是使用文件I/O操作:
```pythonwith open('log.txt', 'w') as f: for i in range(100): f.write(str(i) + '\n')```这样会生成`log.txt`文件,内容为123...100。print函数支持将输出结果写入文件。默认输出到`sys.stdout`,即控制台。如果需要输出到文件,可以指定file参数:
```pythonwith open('log.txt', 'w') as f: for i in range(100): print(str(i), file=f)```注意:print函数会自动添加换行符,不需要手动添加。print函数支持多个参数,提供了flexible的输出控制:
```pythonprint(value, sep=' ', end='\n', file=sys.stdout, flush=False)```- `value`:要打印的值。- `sep`:字符串分隔符,默认为空格。- `end`:结束符,默认为换行。- `file`:目标流,默认为`sys.stdout`。- `flush`:强制刷新流输出,默认为False。转载地址:http://uela.baihongyu.com/