写入TXT文件时触发FileNotFoundError问题排查求助
Let's break down why you're hitting this error even though the target directory exists, and walk through actionable fixes step by step.
Possible Causes & Solutions
1. Windows Path Length Limit
Windows has a default maximum path length of 260 characters. Looking at the error path:
C:/Users/Info/Desktop/Dissertation/Impression Management/Analyse/10 CEO Transcripts/Interviews WORK/3032771020/Earnings Calls Texts/2017/February 22, 2017_Event Brief of Q4 2016 Arris International PLC Earnings Call Q4 2016 and Acquisition Update - Final.pdf.txt
This is almost certainly exceeding that limit, which triggers the FileNotFoundError even if the directory is valid.
Fix:
- Enable long path support (requires Windows 10 1607+/Windows Server 2016+):
- Open Registry Editor (
regedit) - Navigate to
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem - Set the
LongPathsEnabledDWORD value to1(create it if it doesn't exist)
- Open Registry Editor (
- Alternatively, shorten the filename or directory structure for this specific case.
2. Race Condition Between Directory Check & File Write
Your code checks if the directory exists, but there's a tiny window where the directory could be deleted/moved after the check but before opening the file. While you confirm the directory exists, this is a common oversight in file handling.
Fix:
Replace the directory check with os.makedirs (which ensures the directory exists right before writing) and use os.path.join for more reliable path construction:
import os # Build directory path safely dir_path = os.path.join( 'C:/Users/Info/Desktop/Dissertation/Impression Management/Analyse', '10 CEO Transcripts/Interviews WORK', str(deal_no), 'Earnings Calls Texts', str(year) ) # Create directory if it doesn't exist (no error if it does) os.makedirs(dir_path, exist_ok=True) # Build full file path file_path = os.path.join(dir_path, f'{fulldate}_{file}.txt') # Write to file with open(file_path, 'w') as filehandle: for item in textlist_new: filehandle.write(f'{item}\n')
3. Hidden Invalid Characters in Filename
While your filename looks valid at a glance, variables like fulldate or file might contain invisible characters (like non-breaking spaces) or Windows-reserved symbols that break the path.
Fix:
Sanitize the filename to remove/replace invalid characters:
import re def sanitize_filename(filename): # Replace all Windows-invalid filename characters with underscores return re.sub(r'[<>:"/\\|?*]', '_', filename) # Clean variables before building the path clean_fulldate = sanitize_filename(fulldate) clean_file = sanitize_filename(file) file_path = os.path.join(dir_path, f'{clean_fulldate}_{clean_file}.txt')
4. Permission Restrictions
It's possible that for this specific directory, your user account lacks write permissions (even if other files in the parent structure worked).
Fix:
Right-click the target directory > Properties > Security tab > Verify your user account has "Write" permissions enabled.
Final Takeaway
The most likely issue here is the long path length, since your code worked for shorter filenames/directories. Start by enabling long path support, then switch to using os.makedirs and os.path.join for more robust, cross-platform path handling.
内容的提问来源于stack exchange,提问作者xxgaryxx

