2016-11-23 172 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”:-)