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.

Steinar Lima
  • 7,644
  • 2
  • 39
  • 40
user128956
  • 123
  • 1
  • 14

3 Answers3

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.

abarnert
  • 354,177
  • 51
  • 601
  • 671
roippi
  • 25,533
  • 4
  • 48
  • 73
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

mhlester
  • 22,781
  • 10
  • 52
  • 75
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))
Adam Smith
  • 52,157
  • 12
  • 73
  • 112