Python 列表程序不工作

Python 列表程序不工作,python,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)

我已经编写了一个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
Test List
ball
apple
cat
digger
elephant  
它显示如下:

['Shopping List\n']
['Shopping List\n', 'Soap\n']
['Shopping List\n', 'Soap\n', 'Washing Up Liquid\n']
我想知道是否有人能帮助我理解它为什么会这样,以及如何修复它。 仅供参考,我正在使用python 2.6.1

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

这是文本文件:

Shopping List
Soap
Washing Up Liquid
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'] 
同样,任何故障排除都会有所帮助。 谢谢


另外,我现在在read中使用Python2.7.9,您在每行读取后都将打印整个列表。您只需打印当前行:

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
,因为您还没有返回任何更改;您希望从项目的开头和结尾添加额外的空格,因此最小值为:

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

因为它会将每一行追加到列表中。您应该独立
打印mylist
,这样它就不会在
for
循环中