original_stdout = sys.stdout withopen('output.txt', 'w') as f: sys.stdout = f # Change the standard output to the file we created. inspect(ids_dir) sys.stdout = original_stdout # Reset the standard output to its original value
有选择的打印输出到文件
如果想要有选择性的把打印内容输出到文件,可以如下:
python
1 2
print("Hello Python!", file=open('output.txt','a')) print("We are printing to file.", file=open('output.txt','a'))