Python生成日志路径触发TypeError: not all arguments converted报错求助
Hey there! Let's break down what's causing this error and fix it quickly.
The Root Cause
Your line:
log_file_path = os.path.join(log_dir, 'Params.txt' % datetime.strftime(datetime.today(), '%Y%m%d'))
is throwing an error because you're using the string formatting operator % on the string 'Params.txt'—but this string has no placeholder (like %s) where Python can insert the formatted date string. Python sees you're passing a value to format with, but nowhere to put it, hence the TypeError.
You want to append the date to your log filename (like Params_20240520.txt), right? Here are a few clean ways to do that:
Solution 1: Use F-Strings (Recommended for Python 3.6+)
F-strings are the most readable and concise way to format strings now:
from datetime import datetime import os log_dir = os.path.abspath(os.path.join(__file__, "../../", 'logs')) # Embed the formatted date directly in the filename string log_file_path = os.path.join(log_dir, f'Params_{datetime.today().strftime("%Y%m%d")}.txt')
Solution 2: String Concatenation
If you prefer a more explicit approach, build the filename by concatenating strings:
from datetime import datetime import os log_dir = os.path.abspath(os.path.join(__file__, "../../", 'logs')) date_str = datetime.today().strftime("%Y%m%d") log_file_path = os.path.join(log_dir, 'Params_' + date_str + '.txt')
Solution 3: Use the .format() Method
For older Python versions (pre-3.6), the .format() method works reliably:
from datetime import datetime import os log_dir = os.path.abspath(os.path.join(__file__, "../../", 'logs')) date_str = datetime.today().strftime("%Y%m%d") log_file_path = os.path.join(log_dir, 'Params_{}.txt'.format(date_str))
All these approaches will generate a filename like Params_20240520.txt (with today's date) and avoid the formatting error you ran into.
内容的提问来源于stack exchange,提问作者J.Doe

