I.Abdelsalam February 2016

Python redirect/write output to file?

I want to write the output write the output in a file, but all I got was "None" even for words with synonyms.

Note: when I am not writing in the file the output it works perfectly fine Another note: the output appears on the screen whether i am writing to a file or not, but I get "None" in the file, is theres anyway to fix it. [im using python V2.7 Mac version]

file=open("INPUT.txt","w") #opening a file
for xxx in Diacritics:
    print xxx
    synsets = wn.get_synsetids_from_word(xxx) or []
    for s in synsets:
          file.write(str(wn._items[s].describe()))

Answers


Michal Frystacky February 2016

I tried to simplify the question and rewrite your code so that its an independent test that you should be able to run and eventually modify if that was the problem with your code.

test = "Is this a real life? Is this fantasy? Caught in a test slide..."
with open('test.txt', 'w') as f:
    for word in test.split():
        f.write(word) # test.txt output: Isthisareallife?Isthisfantasy?Caughtinatestslide...

A side note it almost sounds like you want to append rather than truncate, but I am not sure, so take a look at this.

The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). If mode is omitted, it defaults to 'r'. The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability. (Appending 'b' is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.) See below for more possible values of mode.


Ethan Furman February 2016

file.write() is going to write whatever is returned by the describe() command. Because 'None' is being written, and because output always goes to the screen, the problem is that describe is writing to the screen directly (probably with print) and returning None.

You need to use some other method besides describe, or give the correct parameters to describe to have it return the strings instead of printing them, or file a bug report. (I am not familiar with that package, so I don't know which is the correct course of action.)

Post Status

Asked in February 2016
Viewed 2,900 times
Voted 10
Answered 2 times

Search




Leave an answer