Write user input to file python

烈酒焚心 提交于 2021-02-17 07:02:23

问题


I can't figure out how to write the user input to an existing file. The file already contains a series of letters and is called corpus.txt . I want to take the user input and add it to the file , save and close the loop.

This is the code I have :

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

Any suggestions?

The user info code is :

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]

I also tried this :

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

Because I want the user input to be added to the file and not deleting what is already there, but nothing works.

Please help!


回答1:


Open the file in append mode by using "a" as the mode.

For example:

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

Then write to the file and the text should be appended to the end of the file.




回答2:


That code example works for me:

#!/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")

The "with open as" is a convenient way in python to open a file, do something with it while within the block defined by the "with" and let Python handles the rest once you exit it (like, for example, closing the file).

If you want to write the input from the user, you can replace mycorpus with your input (I am not too sure what you want to do from your code snippets).

Note that no carriage return is added by the write method. You probably want to append a "\n" at the end :-)



来源:https://stackoverflow.com/questions/40775658/write-user-input-to-file-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!