如何在python中将数据写入文本文件?

时间:2016-02-05 13:26:06

标签: python python-3.x

这是我到目前为止所做的:

def main():
    infoList = [] 
    count = 0

    while True:
        firstname = input('Please enter your first name: ')
        mystring = str(firstname)
        lastname = input('Please enter your last name: ')
        mystring2 = str(lastname)
        telephoneno = input('Please enter your telephone number: ')
        mystring3 = str(telephoneno)
        contiinue = input('Continue (y = yes): ')
        if contiinue == 'y':
            count = count + 1
        else:
            print ("File Written")
            break

        file = open('filename', 'a');
        file.write(data.to_string());
        file.close();

 main()

我试图让程序将输入写为文本文件,但允许添加新信​​息添加到文本文件中,而不是删除已写入的内容。

每当我尝试运行程序时,它都会说main()有问题,还有名称错误,因为数据没有定义?

3 个答案:

答案 0 :(得分:3)

要添加到@ Clodion的答案,我会使用<div class="btn-group" role="group" aria-label=""> @Html.ActionLink("All categories","Index",0,new { @class = "btn btn-default" }) @foreach(var category in ViewBag.AllCategories) { @Html.ActionLink((string) category.Name, "Index",new { categoryId = category.CategoryId}, new { @class="btn btn-default"}) } </div> 关键字

with

答案 1 :(得分:1)

尝试:

def main():
    infoList = [] 
    count = 0

    while True:
        mystring = input('Please enter your first name: ')
        mystring2 = input('Please enter your last name: ')
        mystring3 = input('Please enter your telephone number: ')
        contiinue = input('Continue (y = yes): ')
        if contiinue == 'y':
            count = count + 1
        else:
            print ("File Written")
            break

        data = mystring + mystring2 + mystring3
        file = open('filename', 'a');
        file.write(data);
        file.close();

main()

main()

之前有一个空格

答案 2 :(得分:0)

my_file = '/home/user/file.txt'

def add_code(my_file, permission, code):
    f = open(my_file, permission)
    f.write(code + '\n')
    f.close()

def main():
    infoList = []
    count = 0

    while True:
        mystring = input('Please enter your first name: ')
        add_code(my_file, 'a+', mystring)

        mystring2 = input('Please enter your last name: ')
        add_code(my_file, 'a+', mystring2)

        mystring3 = input('Please enter your telephone number: ')
        add_code(my_file, 'a+', mystring3)

        contiinue = input('Continue (y = yes): ')

        if contiinue == 'y':
            count = count + 1
        else:
            print ("File Written")
            break
main()