1

I have list of elements and I want to write below elements to file using print() function using python.

Python gui: version 3.3

Sample code:

D = {'b': 2, 'c': 3, 'a': 1}
flog_out = open("Logfile.txt","w+") 
for key in sorted(D):
    print(key , '=>', D[key],flog_out)
flog_out.close()

Output when I run in IDLE gui:

a => 1 <_io.TextIOWrapper name='Logfile.txt' mode='w+' encoding='cp1252'>
b => 2 <_io.TextIOWrapper name='Logfile.txt' mode='w+' encoding='cp1252'>
c => 3 <_io.TextIOWrapper name='Logfile.txt' mode='w+' encoding='cp1252'>

I don't see any line written in the output file. I tried using the flog_out.write(), it looks we can pass one argument in write() function. Can anybody look into my code and tell if I'm missing something.

1
  • Can you please add your expected output to your question? Commented Jan 24, 2014 at 20:50

3 Answers 3

6

If you are specifying a file-like object to print, you need to use a named kwarg (file=<descriptor>) syntax. All unnamed positional arguments to print will be concatenated together with a space.

i.e.

print(key , '=>', D[key], file=flog_out)

works.

Sign up to request clarification or add additional context in comments.

Comments

2

From Python Docs

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

All of your arguments, key, '=>', D[key], and flog_out, are packed into *objects and printed to stdout. You need to add a keyword argument for flog_out like so:

print(key , '=>', D[key], file=flog_out)

in order to prevent it from treating it like just-another-object

Comments

0
D = {'b': 2, 'c': 3, 'a': 1}
flog_out = open("Logfile.txt","w+") 
for key in sorted(D):
    flog_out.write("{} => {}".format(key,D[key]))
flog_out.close()

Though if I were writing it I'd use a context manager and dict.items()

D = {'b': 2, 'c': 3, 'a': 1}
with open("Logfile.txt","w+") as flog_out:
    for key,value in sorted(D.items()):
        flog_out.write("{} => {}".format(key,value))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.