Skip to content Skip to sidebar Skip to footer

Python: Writing To A Text File

I want my code to write certain errors to text file. It's copying files over, and I want to write the 'un-copied' files to a text file for a record. I have my script appending an a

Solution 1:

This is an example of an XY problem: You want to do something, think of a solution, find a problem with that solution, and ask for help with that. I'm assuming that although you could do logging yourself (as you are trying), but using Python's built in logger will make more sense. They've already done most of what you need, all you need to do is import it, configure it, and use it.

import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

example.log:

DEBUG:root:This message should go to the log file
INFO:root:So should this
WARNING:root:And this, too

This also supports things like command line logging level setting, and a bunch of other stuff.

DocsTutorial

Solution 2:

Try changing a to a+, which tells python to create a file if it doesn't exist.

text_file = open("%s_copy_log.txt" % username, "a+")

Further Reading on Python File IO Types

Solution 3:

I'm not sure what your application structure looks like, but if you have a number of users and want each username to have its own log (why?) when perhaps the best way would be something like:

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
admin_handler = logging.FileHandler("app.log")
admin_handler.setLevel(logging.DEBUG)
logger.addHandler(admin_handler)
# this will write ALL events to one location
user_logger = logger.getChild("userlog")

deflogin(username, password):
    if verify(username, password):  # however you're doing this
        user_logger.addHandler(logging.FileHandler("%s.log" % username))
        user_logger.setLevel(logging.WARNING)  # or maybe logging.INFO?
        user_logger.info("%s logged in" % username)

        # authenticate the user as you currently doelse:
        logger.warning("%s attempted login with bad password!" % username)

        # prompt the user as you currently dodeflogout():
    user_logger.handlers = []  # remove previous user logger# de-authenticate as normaldefuser_log_something(the_thing):
    if the_thing.is(something_critical):
        user_logger.critical(the_thing)

Post a Comment for "Python: Writing To A Text File"