2016-11-23 245 views
0

我無法弄清楚如何將用戶輸入寫入現有文件。該文件已包含一系列字母,稱爲corpus.txt。我想獲取用戶輸入並將其添加到文件中,保存並關閉循環。將用戶輸入寫入文件python

這是我的代碼:

if user_input == "q": 
    def write_corpus_to_file(mycorpus,myfile): 
     fd = open(myfile,"w") 
     input = raw_input("user input") 
     fd.write(input) 
    print "Writing corpus to file: ", myfile 
    print "Goodbye" 
    break 

有什麼建議?

用戶信息的代碼是:

def segment_sequence(corpus, letter1, letter2, letter3): 
    one_to_two = corpus.count(letter1+letter2)/corpus.count(letter1) 
    two_to_three = corpus.count(letter2+letter3)/corpus.count(letter2) 

    print "Here is the proposed word boundary given the training corpus:" 

    if one_to_two < two_to_three: 
     print "The proposed end of one word: %r " % target[0] 
     print "The proposed beginning of the new word: %r" % (target[1] + target[2]) 

    else: 
     print "The proposed end of one word: %r " % (target[0] + target[1]) 
     print "The proposed beginning of the new word: %r" % target[2] 

我也試過這樣:

f = open(myfile, 'w') 
mycorpus = ''.join(corpus) 
f.write(mycorpus) 
f.close() 

因爲我要被添加到該文件的用戶輸入,而不是刪除的內容已經有了,但沒有用。

請幫忙!

+0

當你有答案時,你不應該刪除你的問題。問題和答案應該保持在對其他人有用的情況下。可能你可以接受一個正確答案。 – skyking

回答

1

使用「a」作爲模式以追加模式打開文件。

例如:

f = open("path", "a") 

然後寫入文件和文本應該附加到該文件的結束。

0

的示例代碼工作對我來說:

#!/usr/bin/env python 

def write_corpus_to_file(mycorpus, myfile): 
    with open(myfile, "a") as dstFile: 
     dstFile.write(mycorpus) 

write_corpus_to_file("test", "./test.tmp") 

的「開放的」,是在python的便捷方式打開一個文件,用它做的東西,而由「與」確定的區塊內讓Python在退出時處理其餘部分(例如,關閉文件)。

如果你想寫用戶的輸入,你可以用你的input(我不太清楚你想從你的代碼片段中做什麼)代替mycorpus

請注意,寫入方法不會添加回車符。你可能想在最後追加一個「\ n」:-)