Unable To Write List Of Elements To A File Using Python
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
Solution 1:
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.
Solution 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
Solution 3:
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}
withopen("Logfile.txt","w+") as flog_out:
for key,value insorted(D.items()):
flog_out.write("{} => {}".format(key,value))
Post a Comment for "Unable To Write List Of Elements To A File Using Python"