2016-11-23 11 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が終了したら(例えば、ファイルを閉じるなど)、残りの部分を処理させます。

ユーザーからの入力を書きたい場合は、mycorpusinputに置き換えることができます(コードスニペットから何をしたいか分かりません)。

writeメソッドによってキャリッジリターンが追加されないことに注意してください。あなたはおそらく最後に「\ n」を付けたいと思うでしょう:-)

関連する問題