PYTHON如何将str输入文本写入文本fi

2024-06-26 14:28:12 发布

您现在位置:Python中文网/ 问答频道 /正文

每次我尝试将我为“ime”或“autor”编写的文本保存到外部文本文件时,都会遇到问题。任何关于如何解决这个问题的建议,以便我可以以一个有组织的“类别”的方式存储信息将不胜感激。在

def unosenje_knjiga():
    file = open("2.rtd", "a")
    ime = str(input("Ime knjige:"))
    while len(ime) <= 3:
        print("Molimo Vas unesite ime knjige ponovo!")
        ime = str(input("Ime knjige:"))

    autor = str(input("Autor knjige:"))
    while len(autor) <= 0:
        print("Molimo Vas unesite ime autora ponovo!")
        ime = str(input("Autor knjige:"))

    isbn = str(input("ISBN knjige:"))
    while len(isbn) <= 0:
        print("Molimo Vas unesite ISBN knjige ponovo!")
        ime = str(input("ISBN knjige:"))

Tags: inputlenprintisbnwhilestrvasime
2条回答
  1. 不能使用ime = str(input("Ime knjige:"));

而是使用 ime = raw_input("Ime knjige:");因为如果使用ime = input("..."),python会尝试将“…”解释为有效的python表达式

例如,键入shell

     str = input("enter input")

作为输入类型5+4,则

^{pr2}$

结果将是9,因为如果使用输入,则会计算输入的内容

  1. 如果你想写一些东西到一个文件,你必须打开一个文件的句柄,然后对它进行写/读,完成后关闭文件句柄(搜索'python file input output')

    #!/usr/bin/python

    # Open a file

    fo = open("foo.txt", "wb")//二进制文件io

    fo.write( "Python is a great language.\nYeah its great!!\n");

    # Close opened file

    {/cdp}

https://www.tutorialspoint.com/python/python_files_io.htm

您可以通过file.write(s)将字符串s写入打开的文件

存储数据的一种简单格式是Comma Separated Values (CSV)。在

因此,您只需将三个字符串连接在一起并将它们写入文件:

s = '"%s","%s","%s"' % (ime,autor,isbn)
file.write(s + "\n")

您可能需要修复两个while循环。第二个查询总是设置变量ime而不是autor/isbn。在

相关问题 更多 >