You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将输出保存至文本文件:代码无报错但生成空文件的问题求助

Why Your log.txt Is Empty & How to Fix It

Hey there, let's break down why your code isn't writing anything to log.txt and get it working properly:

The Core Issue: Unflushed Output Buffer

When you redirect sys.stdout to a file, Python uses a buffer to hold output before writing it to disk. By default, this buffer only flushes (writes to disk) when it's full, the program exits, or you explicitly tell it to. In your code, you're closing the file right after printing, which cuts off the buffer before it can write your output to log.txt. That's why the file is empty!

Quick Fixes

Option 1: Manually Flush the Buffer

Add a flush() call before closing the file to force the buffer to write its contents:

import sys
import os
import fnmatch

stdoutOrigin = sys.stdout
sys.stdout = open("log.txt", "w+")

listOfFiles = os.listdir('s:\\')
pattern = "*.txt"
for entry in listOfFiles:
    if fnmatch.fnmatch(entry, pattern):
        print(entry)

sys.stdout.flush()  # This forces the buffer to write to disk
sys.stdout.close()
sys.stdout = stdoutOrigin

Using a with statement to handle the file automatically takes care of flushing and closing, so you don't have to remember manual calls:

import sys
import os
import fnmatch

stdoutOrigin = sys.stdout
with open("log.txt", "w+") as log_file:
    sys.stdout = log_file
    listOfFiles = os.listdir('s:\\')
    pattern = "*.txt"
    for entry in listOfFiles:
        if fnmatch.fnmatch(entry, pattern):
            print(entry)
sys.stdout = stdoutOrigin

Bonus: Get Full File Paths (As You Expected)

Your original goal was to log files and their directories, but right now you're only printing filenames. To get the full path (like S:\example.txt), update your print line to:

print(os.path.join('s:\\', entry))

Other Things to Check

  • Make sure there actually are .txt files in your S: drive root! Test this by running print(os.listdir('s:\\')) directly in your console to see what's there.
  • Verify your program has permission to write to the directory where log.txt is being created (e.g., you might be in a restricted system folder).

内容的提问来源于stack exchange,提问作者Jorge Figueiredo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:28:55