将输出保存至文本文件:代码无报错但生成空文件的问题求助
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
Option 2: Use a Context Manager (Cleaner & Recommended)
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
.txtfiles in your S: drive root! Test this by runningprint(os.listdir('s:\\'))directly in your console to see what's there. - Verify your program has permission to write to the directory where
log.txtis being created (e.g., you might be in a restricted system folder).
内容的提问来源于stack exchange,提问作者Jorge Figueiredo

