在python中添加用户输入

时间:2014-11-11 22:35:47

标签: python python-3.x

我试图使用输入文件名的输入,我想要做的只是让用户输入没有扩展名的文件名。由于唯一适用的文件是.txt文件,让用户输入扩展名似乎是多余的,所以我想添加文件扩展名和代码,这是我到目前为止:

 def create_bills(filename, capacity):
    f = open(filename)
    mytable = mkHashTable(capacity)
    for line in f:
        txt = line.strip().split(' $')
        person = Person(txt[0], txt[1])
        if not person.name in keys(mytable):
            mytable = put(mytable, person.name, person.bill)
        elif person.name in keys(mytable):
            index = indexOf(mytable, person.name)
        else:
            pass

def main():
    capacity = int(input("Size of Hashtable: "))
    file = input("Enter file to be read: ")
    filename = (file +'.txt')
    create_bills(filename, capacity)

我不确定如何实际处理此问题并将.txt添加到用户输入。 例如:

  
    
      

请输入文件名:       帮助

    
  

.... help.txt

错误:

Traceback (most recent call last):
  File "C:/Users/Th3M1k3/Desktop/python/beeb lab/bieberhash.py", line 30, in <module>
    main()
  File "C:/Users/Th3M1k3/Desktop/python/beeb lab/bieberhash.py", line 28, in main
    create_bills(filename, capacity)
  File "C:/Users/Th3M1k3/Desktop/python/beeb lab/bieberhash.py", line 12, in create_bills
    f = open(filename, '.txt')
ValueError: invalid mode: '.txt'

1 个答案:

答案 0 :(得分:0)

main中,您已将.txt添加到用户输入的文件名中。您无需在create_bills()的公开呼叫中再次添加它。