列表程序不起作用

时间:2015-02-28 13:27:28

标签: python

我编写了一个python程序作为购物清单或其他一些列表编辑器。它按原样显示列表,然后询问您是否要添加内容,然后询问您是否要查看列表的最新版本。这是代码:

#!/usr/bin/python
import sys
def read():
    f = open("test.txt","r") #opens file with name of "test.txt"
    myList = []
    for line in f:
        myList.append(line)
        print(myList)
    myList = []
    f.close()

def add_to(str):
    newstr = str + "\n"
    f = open("test.txt","a") #opens file with name of "test.txt"
    f.write(newstr)
    f.close()
read()
yes = "yes"
answerone = raw_input("Would you like to add something to the shopping     list?")
if answerone == yes:
    answertwo = raw_input("Please enter an item to go on the list:")
    add_to(bob)
     answerthree = raw_input("Would you like to see your modified list?")
     if answerthree == yes:
        read()
    else:
        sys.exit()
else:
    sys.exit()

当它显示列表时,它会以增加长度的列显示它。 而不是这个,它出现在文本文件中的方式:

Shopping List
Soap
Washing Up Liquid

它显示如下:

['Shopping List\n']
['Shopping List\n', 'Soap\n']
['Shopping List\n', 'Soap\n', 'Washing Up Liquid\n']

我想知道是否有人可以帮助我理解为什么会这样做,以及如何解决它。     仅供参考我使用的是python 2.6.1

编辑:感谢所有评论和回答的人。我现在正在尝试编辑代码,使其按字母顺序对列表进行排序,但它不起作用。我已经编写了一段测试代码来尝试使其工作(这将在read()函数中):

#!usr/bin/python
f = open("test.txt","r") #opens file with name of "test.txt"
myList = []
for line in f:
    myList.append(line)
f.close()
print myList
subList = []
for i in range(1, len(myList)):
    print myList[i]
    subList.append(myList[i])


subList.sort()
print subList

这是文本文件:

Test List
ball
apple
cat
digger
elephant  

这是输出:

Enigmatist:PYTHON lbligh$ python test.py
['Test List\n', 'ball\n', 'apple\n', 'cat\n', 'digger\n', 'elephant']
ball

apple

cat

digger

elephant
['apple\n', 'ball\n', 'cat\n', 'digger\n', 'elephant'] 

再一次,任何疑难解答都会有所帮助。 感谢

P.S我现在正在使用python 2.7.9

1 个答案:

答案 0 :(得分:1)

在阅读中,您将在每行读取后打印整个列表。您只需要打印当前行:

def read():
    f = open("test.txt","r") #opens file with name of "test.txt"
    myList = []
    for line in f:
        myList.append(line)
        print(line)
    myList = [] # also you are setting it to empty here
    f.close()

此外,您应该使用with语句来确保文件的关闭;并且没有理由使用myList,因为您尚未返回任何更改;并且您希望从项目的开头和结尾添加strip()额外的空格,因此最小值为:

def read():
    with open('test.txt') as f:
        for line in f:
            line = line.strip()
            print line  # this is python 2 print statement

如果您需要返回一个值:

def read():
    my_list = []
    with open('test.txt') as f:
        for line in f:
            line = line.strip()
            my_list.append(line)
            print line

    return my_list