MySQL documentation says:
SQL prepared statements (PREPARE, EXECUTE, DEALLOCATE PREPARE)
can be used in stored procedures, but not stored functions or triggers.
Thus, stored functions and triggers cannot use dynamic SQL
(where you construct statements as strings and then execute them).
So no - you can't write data to file which name is dynamically created from a trigger.
Since you can't use dynamic sql but you also approve single file name and append data to it you can load data to temporary file, append results of the query and then output full results to a file. Of course it will work only if there is no other need to use dynamically created query except file name.
On example:
DELIMITER $$
CREATE TRIGGER rewrite_file AFTER INSERT tableName
BEGIN
CREATE TEMPORARY TABLE IF NOT EXISTS temp(
pk BIGINT
);
LOAD DATA INFILE 'c:/somefile.txt' INTO TABLE temp
LINES TERMINATED BY '\n';
INSERT INTO temp (pk) SELECT primaryKeyField FROM tableName;
SELECT pk INTO OUTFILE 'c:/somefile.txt'
LINES TERMINATED BY '\n'
FROM temp;
END$$
DELIMITER ;
It will append file c:/somefile.txt on every insert. Of course this solution sucks if your file grows to millions of entries.